Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)....

like image 340
Ignacio Garat Avatar asked Mar 05 '11 21:03

Ignacio Garat


People also ask

How can we sort a list of objects in Java?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

How do you sort a list by date?

Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects. Now in the main method use Collections. sort() method and pass the ArrayList and 'SortItem' class object to it, it will sort the dates, and output will be generated.

How do you sort a list of objects based on an attribute of the objects in Java 8?

Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.

How do I sort a list of custom objects?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.


2 Answers

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());
    }
});
like image 79
pwc Avatar answered Sep 21 '22 19:09

pwc


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();
like image 34
Bozho Avatar answered Sep 21 '22 19:09

Bozho