3
\$\begingroup\$

The class "post" only has simple methods like getters for the ID(long) and number of likes(long). Is how I wrote my method below accomplishing anything? Is it doing what I want it to do? I am a beginner so I am sorry if my question is too stupid.

public class PracticeStats {

Given an array of posts, this method finds the ID of the post that has the most likes. Return -1 if the array is of length 0. If two posts have the same number of likes, return the number of likes of either post. return ID of the post with most likes if the array is non-empty, 0 otherwise

public static long mostLikedPost(Post[] posts) {
    long max = 0;
    for (int i = 0; i< posts.length; i++) {
        long curr = posts[i].getNumLikes();
        if(curr > max) {
            curr = max;
        }
        return posts[i].getID();
    }
    return max;
}
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Advice 1

Judging from the method name mostLikedPost, you expect the most liked post and not its number of likes, so you must have

public static Post mostLikedPost(Post[] posts) ...
              ^^^^

Advice 2

return posts[i].getID();

The above will terminate the entire loop at the very first iteration.

Advice 3

You could use a foreach loop.

Alternative implementation

public static Post mostLikedPost(Post[] posts) {
    long maxLikes = 0;
    Post favoritePost = null;
    
    for (Post post : posts) {
        long currentLikes = post.getNumLikes();
        
        if (maxLikes < currentLikes) {
            maxLikes = currentLikes;
            favoritePost = post;
        }
    }
    
    return favoritePost;
}

With streams API:

public static Post mostLikedPost(Post[] posts) {
    return Arrays.stream(posts)
          .max((p1, p2) -> { 
              return Long.compare(p1.getNumLikes(),
                                  p2.getNumLikes()); 
          }).orElse(null);
}

Hope that helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.