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

private List<Movie> movieItems = null;
public List<Movie> getMovieItems() {
    final int first = 0;
    if (movieItems == null) {
        getPagingInfo();
        movieItems = jpaController.findRange(new int[]{pagingInfo.getFirstItem(), pagingInfo.getFirstItem() + pagingInfo.getBatchSize()});
        Collections.sort(movieItems, new Comparator(){
           public int compare (Object o1, Object o2){
               Date d1 = movieItems.get(((Movie)o1).getMovieId()).getDate();
               Date d2 = movieItems.get(((Movie)o2).getMovieId()).getDate();
               if(d1.before(d2)){
                   movieItems.set(1, (Movie)o1);
                   movieItems.set(2, (Movie)o2);
               }
               return first;
           }
       });
    }
    return movieItems;
}

jpaController is bringing back 4 movies and is giving me the following

java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 4 at java.util.Vector.get(Vector.java:694) at entitybeans.jsf.PeliculaController$1.compare(PeliculaController.java:260) at java.util.Arrays.mergeSort(Arrays.java:1270) at java.util.Arrays.sort(Arrays.java:1210) at java.util.Collections.sort(Collections.java:159) at entitybeans.jsf.PeliculaController.getPeliculaItems(PeliculaController.java:257) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at javax.el.BeanELResolver.getValue(BeanELResolver.java:302) at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175) at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72) at com.sun.el.parser.AstValue.getValue(AstValue.java:116) at com.sun.el.parser.AstValue.getValue(AstValue.java:163)....

This question is related to java sorting collections

The answer is


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());
    }
});

You can use this:

Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());

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


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

movieItems.sort(Comparator.comparing(Movie::getDate));

You're using Comparators incorrectly.

 Collections.sort(movieItems, new Comparator<Movie>(){
           public int compare (Movie m1, Movie m2){
               return m1.getDate().compareTo(m2.getDate());
           }
       });

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();

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?