Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an ArrayList base on multiple attributes

Tags:

java

sorting

I have an ArrayList of object. The object contain attributes date and value. So I want to sort the objects on the date, and for all objects in the same date I want to sort them on value. How can I do that?

like image 616
Thang Pham Avatar asked Nov 30 '10 02:11

Thang Pham


People also ask

How do you sort a list of objects based on an attribute of the 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.

Can Comparable be used to sort on multiple fields?

1. Creating Comparators for Multiple Fields. To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.

Is there a sort method for ArrayList?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.


2 Answers

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());
like image 80
harto Avatar answered Oct 01 '22 17:10

harto


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);  
  } 
like image 38
卢声远 Shengyuan Lu Avatar answered Oct 01 '22 17:10

卢声远 Shengyuan Lu