gstackoverflow
gstackoverflow

Reputation: 36984

guava. find element in Collection by criteria

I have this code.

CommentModel lastUserComment = comments.iterator().next();
        for (CommentModel comment : comments) {
            if (comment.getCreationtime().after(lastUserComment.getCreationtime())) {
                lastUserComment = comment;
            }
        }

I want to replace it using guava.

If getCreationtime() returned int I could to use something like this: How to get max() element from List in Guava

Are there in Guava tool for resolving my problem?

Upvotes: 2

Views: 315

Answers (1)

Tom Verelst
Tom Verelst

Reputation: 15992

You can just compare the times.

final Ordering<CommentModel> o = new Ordering<CommentModel>() {
    @Override
    public int compare(final CommentModel left, final CommentModel right) {
        return left.getCreationTime().compareTo(right.getCreationTime());
    }
};
return o.max(comments);

Upvotes: 6

Related Questions