[java] How to sort a Collection<T>?

I have a generic Collection and am trying to work out how I can sort the items contained within it. I've tried a few things but I can't get any of them working.

This question is related to java sorting collections

The answer is


Here is an example. (I am using CompareToBuilder class from Apache for convenience, although this can be done without using it.)

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.builder.CompareToBuilder;

public class Tester {
    boolean ascending = true;

    public static void main(String args[]) {
        Tester tester = new Tester();
        tester.printValues();
    }

    public void printValues() {
        List<HashMap<String, Object>> list =
            new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map =
            new HashMap<String, Object>();

        map.put( "actionId", new Integer(1234) );
        map.put( "eventId",  new Integer(21)   );
        map.put( "fromDate", getDate(1)        );
        map.put( "toDate",   getDate(7)        );
        list.add(map);

        map = new HashMap<String, Object>();
        map.put( "actionId", new Integer(456) );
        map.put( "eventId",  new Integer(11)  );
        map.put( "fromDate", getDate(1)       );
        map.put( "toDate",   getDate(1)       );
        list.add(map);

        map = new HashMap<String, Object>();
        map.put( "actionId", new Integer(1234) );
        map.put( "eventId",  new Integer(20)   );
        map.put( "fromDate", getDate(4)        );
        map.put( "toDate",   getDate(16)       );
        list.add(map);

        map = new HashMap<String, Object>();
        map.put( "actionId", new Integer(1234) );
        map.put( "eventId",  new Integer(22)   );
        map.put( "fromDate", getDate(8)        );
        map.put( "toDate",   getDate(11)       );
        list.add(map);


        map = new HashMap<String, Object>();
        map.put( "actionId", new Integer(1234) );
        map.put( "eventId",  new Integer(11)   );
        map.put( "fromDate", getDate(1)        );
        map.put( "toDate",   getDate(10)       );
        list.add(map);

        map = new HashMap<String, Object>();
        map.put( "actionId", new Integer(1234) );
        map.put( "eventId",  new Integer(11)   );
        map.put( "fromDate", getDate(4)        );
        map.put( "toDate",   getDate(15)       );
        list.add(map);

        map = new HashMap<String, Object>();
        map.put( "actionId", new Integer(567) );
        map.put( "eventId",  new Integer(12)  );
        map.put( "fromDate", getDate(-1)      );
        map.put( "toDate",   getDate(1)       );
        list.add(map);

        System.out.println("\n Before Sorting \n ");
        for( int j = 0; j < list.size(); j++ )
            System.out.println(list.get(j));

        Collections.sort( list, new HashMapComparator2() );

        System.out.println("\n After Sorting \n ");
        for( int j = 0; j < list.size(); j++ )
            System.out.println(list.get(j));
    }

    public static Date getDate(int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }

    public class HashMapComparator2 implements Comparator {
        public int compare(Object object1, Object object2) {
            if( ascending ) {
                return new CompareToBuilder()
                    .append(
                        ((HashMap)object1).get("actionId"),
                        ((HashMap)object2).get("actionId")
                    )
                    .append(
                        ((HashMap)object2).get("eventId"),
                        ((HashMap)object1).get("eventId")
                    )
                .toComparison();
            } else {
                return new CompareToBuilder()
                    .append(
                        ((HashMap)object2).get("actionId"),
                        ((HashMap)object1).get("actionId")
                    )
                    .append(
                        ((HashMap)object2).get("eventId"),
                        ((HashMap)object1).get("eventId")
                    )
                .toComparison();
            }
        }
    }
}

If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!


Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }

You can't if T is all you get. It must be injected by the provider:

Collection<T extends Comparable>

or pass in the Comparator

Collections.sort(...)

A Collection does not have an ordering, so wanting to sort it does not make sense. You can sort List instances and arrays, and the methods to do that are Collections.sort() and Arrays.sort()


I came across a similar problem. Had to sort a list of 3rd party class (objects).

List<ThirdPartyClass> tpc = getTpcList(...);

ThirdPartyClass does not implement the Java Comparable interface. I found an excellent illustration from mkyong on how to approach this problem. I had to use the Comparator approach to sorting.

//Sort ThirdPartyClass based on the value of some attribute/function
Collections.sort(tpc, Compare3rdPartyObjects.tpcComp);

where the Comparator is:

public abstract class Compare3rdPartyObjects {

public static Comparator<ThirdPartyClass> tpcComp = new Comparator<ThirdPartyClass>() {

    public int compare(ThirdPartyClass tpc1, ThirdPartyClass tpc2) {

        Integer tpc1Offset = compareUsing(tpc1);
        Integer tpc2Offset = compareUsing(tpc2);

        //ascending order
        return tpc1Offset.compareTo(tpc2Offset);

    }
};

//Fetch the attribute value that you would like to use to compare the ThirdPartyClass instances 
public static Integer compareUsing(ThirdPartyClass tpc) {

    Integer value = tpc.getValueUsingSomeFunction();
    return value;
}
}

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

You have two basic options provided by java.util.Collections:

Depending on what the Collection is, you can also look at SortedSet or SortedMap.


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?