[java] Sort Java Collection

I have a Java collection:

Collection<CustomObject> list = new ArrayList<CustomObject>();

CustomObject has an id field now before display list I want to sort this collection by that id.

Is there any way I could that do that?

This question is related to java sorting collections

The answer is


You should implement the Comparator interface.

example:

public class CustomComparator implements Comparator<CustomObject> 
{
    @Override
    public int compare(CustomObject o1, CustomObject o2) {
        return o1.getId().compareTo(o2.getId());
    }
}

Then you can use the Collections classes Collections.sort() method:

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

Use sort.

You just have to do this:

All elements in the list must implement the Comparable interface.

(Or use the version below it, as others already said.)


You can also use:

Collections.sort(list, new Comparator<CustomObject>() {
    public int compare(CustomObject obj1, CustomObject obj2) {
        return obj1.id - obj2.id;
    }
});
System.out.println(list);

A lot of correct answers, but I haven't found this one: Collections cannot be sorted, you can only iterate through them.

Now you can iterate over them and create a new sorted something. Follow the answers here for that.


To be super clear, Collection.sort(list, compartor) does not return anything so something like this list = Collection.sort(list, compartor); will throw an error (void cannot be converted to [list type]) and should instead be Collection.sort(list, compartor)


SortedSet and Comparator. Comparator should honour the id field.


The question is: "Sort Collection". So you can't use Collections.sort(List<T> l, Comparator<? super T> comparator).

Some tips:

For Collection type:

Comparator<String> defaultComparator = new Comparator<String>() {
   @Override
   public int compare(String o1, String o2) {
       return o1.compareTo(o2);
   }
};

Collection<String> collection = getSomeStringCollection();
String[] strings = collection.toArray(new String[collection.size()]);
Arrays.sort(strings, defaultComparator);
List<String> sortedStrings = Arrays.asList(strings);

Collection<String> collection = getSomeStringCollection();
List<String> list = new ArrayList(collection);
Collections.sort(list, defaultComparator);
collection = list; // if you wish

For List type:

List<String> list = getSomeStringList();
Collections.sort(list, defaultComparator);

For Set type:

Set<String> set = getSomeStringSet();
// Than steps like in 'For Collection type' section or use java.util.TreeSet
// TreeSet sample:
// Sorted using java.lang.Comparable.
Set<String> naturalSorted = new TreeSet(set);

Set<String> set = getSomeStringSet();
Set<String> sortedSet = new TreeSet(defaultComparator);
sortedSet.addAll(set);

Java 8 version. There is java.util.List#sort(Comparator<? super E> c) method

List<String> list = getSomeStringList();
list.sort(defaultComparator);

or

List<String> list = getSomeStringList();
list.sort((String o1, String o2) -> o1.compareTo(o2));

or for types that implements Comparable:

List<String> list = getSomeStringList();
list.sort(String::compareTo);

As of Java 8 you now can do it with a stream using a lambda:

list.stream().sorted(Comparator.comparing(customObject::getId))
             .foreach(object -> System.out.println(object));

Implement the Comparable interface on your customObject.


You can use java Custom Class for the purpose of sorting.


A slightly different example say if you have a class that doesn't implement Comparable but you still want to sort it on a field or method.

Collections.sort(allMatching, new Comparator<ClassOne>() {
  @Override public int compare(final ClassOne o1, final ClassOne o2) {
    if (o1.getMethodToSort() > o2.getMethodToSort()) {
      return 1;
    } else if (o1.getMethodToSort() < o2.getMethodToSort()) {
      return -1;
    }  
    return 0;
  }
});

Comparator is the way

Also See


With Java 8 you have several options, combining method references and the built-in comparing comparator:

import static java.util.Comparator.comparing;

Collection<CustomObject> list = new ArrayList<CustomObject>();

Collections.sort(list, comparing(CustomObject::getId));
//or
list.sort(comparing(CustomObject::getId));

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?