How to sort a List of objects by their date (java collections, List<Object>)

前端 未结 6 1361
迷失自我
迷失自我 2020-12-25 15:20
private List movieItems = null;
public List getMovieItems() {
    final int first = 0;
    if (movieItems == null) {
        getPagingInfo(         


        
相关标签:
6条回答
  • 2020-12-25 15:26

    Do not access or modify the collection in the Comparator. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.

    Date itself is comparable, so, using generics:

    class MovieComparator implements Comparator<Movie> {
        public int compare(Movie m1, Movie m2) {
           //possibly check for nulls to avoid NullPointerException
           return m1.getDate().compareTo(m2.getDate());
        }
    }
    

    And do not instantiate the comparator on each sort. Use:

    private static final MovieComparator comparator = new MovieComparator();
    
    0 讨论(0)
  • 2020-12-25 15:26

    You can use this:

    Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());
    
    0 讨论(0)
  • 2020-12-25 15:30

    You're using Comparators incorrectly.

     Collections.sort(movieItems, new Comparator<Movie>(){
               public int compare (Movie m1, Movie m2){
                   return m1.getDate().compareTo(m2.getDate());
               }
           });
    
    0 讨论(0)
  • 2020-12-25 15:43

    In your compare method, o1 and o2 are already elements in the movieItems list. So, you should do something like this:

    Collections.sort(movieItems, new Comparator<Movie>() {
        public int compare(Movie m1, Movie m2) {
            return m1.getDate().compareTo(m2.getDate());
        }
    });
    
    0 讨论(0)
  • 2020-12-25 15:52

    In Java 8, it's now as simple as:

    movieItems.sort(Comparator.comparing(Movie::getDate));
    
    0 讨论(0)
  • 2020-12-25 15:52

    I'd add Commons NullComparator instead to avoid some problems...

    0 讨论(0)
提交回复
热议问题