Custom date-based list sorting

I got:

List<Comment> list = new ArrayList<Comment>();

My class Comment contains: id, name and date; I have a function that adds the specified Comments, but I would like to order after that my list by date in descending order. How to do it:

Collections.sort(list, comparator)

?

+3
source share
3 answers

You need to implement Comparator<Comment>one that implements the method comparebased on the date field and passes this object to Collections.sort.

Here is a complete example:

import java.util.*;

class Comment {
    String id, String name;
    Date date;

    public Comment(String id, String name, Date date) {
        this.id = id;
        this.name = name;
        this.date = date;
    }
}


class CommentComparator implements Comparator<Comment> {
    public int compare(Comment o1, Comment o2) {
        return o1.date.compareTo(o2.date);
    }
}


class Test {
    public static void main(String[] args) {
        List<Comment> comments = new ArrayList<Comment>() {{
            long now = System.currentTimeMillis();
            add(new Comment("id1", "second", new Date(now)));
            add(new Comment("id2", "first", new Date(now - 1000)));
            add(new Comment("id3", "third", new Date(now + 1000)));
        }};

        Collections.sort(comments, new CommentComparator());
    }
}
+3
source

You already know what you need to do. Just install de Comparator. It could be something like:

Collections.sort(list, new Comparator<Comment>() {
            @Override
            public int compare(Comment o1, Comment o2) {
                return o1.getDate().compareTo(o2.getDate());
            }
        });

(Maybe you need to check the zeros)

+3
source

One of the fellows mentioned here is to implement a custom Comparator for comments. An alternative approach would be to implement a Comparable interface in a comment class.

import java.util.*;

class Comment implements Comparable<Comment> {
    private String id, String name;
    private Date date;

    public Comment(String id, String name, Date date) {
        this.id = id;
        this.name = name;
        this.date = date;
    }

    public int compareTo(Comment comment) {
        return date.compareTo(o2.date); //Look Ma! Date is Comparable too!
    }

}


class Test {
    public static void main(String[] args) {
        List<Comment> comments = new ArrayList<Comment>() {{
            long now = System.currentTimeMillis();
            add(new Comment("id1", "second", new Date(now)));
            add(new Comment("id2", "first", new Date(now - 1000)));
            add(new Comment("id3", "third", new Date(now + 1000)));
        }};
        Collections.sort(comments);
    }
}

In my example, I used the @aioobe code.

0
source

All Articles