Sort an ArrayList base on multiple attributes

Implement a custom Comparator, then use Collections.sort(List, Comparator). It will probably look something like this:

public class FooComparator implements Comparator<Foo> {
    public int compare(Foo a, Foo b) {
        int dateComparison = a.date.compareTo(b.date);
        return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
    }
}

Collections.sort(foos, new FooComparator());

Java-8 solution using Stream API:

List<Foo> sorted = list.stream()
                        .sorted(Comparator.comparing(Foo::getDate)
                                        .thenComparing(Foo::getValue))
                        .collect(Collectors.toList());

If you want to sort the original list itself:

list.sort(Comparator.comparing(Foo::getDate)
                    .thenComparing(Foo::getValue)); 

public static <T> void sort(List<T> list, final List<Comparator<T>> comparatorList) {  
       if (comparatorList.isEmpty()) {//Always equals, if no Comparator.  
            throw new IllegalArgumentException("comparatorList is empty.");  
       }  
       Comparator<T> comparator = new Comparator<T>() {  
       public int compare(T o1, T o2) {  
               for (Comparator<T> c:comparatorList) {  
                   if (c.compare(o1, o2) > 0) {  
                     return 1;  
                   } else if (c.compare(o1, o2) < 0) {  
                     return -1;  
                   }  
               }  
               return 0;  
         }  
       };  
       Collections.sort(list, comparator);  
  } 

If you want sample code looks like, you can use following:

Collections.sort(foos, new Comparator<Foo>{
    public int compare(Foo a, Foo b) {
        int dateComparison = a.date.compareTo(b.date);
        return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
    }
});

Tags:

Java

Sorting