Dhiraj kadam
Dhiraj kadam

Reputation: 377

Sorting list of objects using objects paramter of Long type

My post class contains following params

Post:
    String PostId
    Long imestamp

List<Post> posts;

I have a list of objects of type Post, how can I sort this list based on Post.timestamp. I tried comparator it asks for int type.

Upvotes: 1

Views: 64

Answers (2)

Anatolii
Anatolii

Reputation: 14670

Just write a Comparator like this:

Comparator<Post> comparator = new Comparator<Post>() {
    @Override
    public int compare(Post o1, Post o2) {
        return Long.compare(o1.timestamp, o2.timestamp);
    }
};

Or let your Post implement Comparable<Post>:

class Post implements Comparable<Post> {
    String PostId;
    Long timestamp = 0;

    @Override
    public int compareTo(@NonNull Post post) {
        return Long.compare(this.timestamp, post.timestamp);
    }
}

Upvotes: 2

Peter1982
Peter1982

Reputation: 518

You can use lambda expresion and have it on one line

 Collections.sort(posts, Comparator.comparing(Post::timestamp));

Upvotes: 2

Related Questions