Sort Java Collection

JavaSortingCollections

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Use a Comparator:

List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
    @Override
    public int compare(CustomObject left, CustomObject right) {
        return left.getId() - right.getId(); // use your logic
    }
};

Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);

Additionally, if CustomObjectimplements Comparable, then just use Collections.sort(list)

With JDK 8 the syntax is much simpler.

List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);

Much simplier

List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);

Simplest

List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);

Obviously the initial code can be used for JDK 8 too.

Solution 2 - Java

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

Solution 3 - Java

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;
  }
});

Solution 4 - Java

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());

Solution 5 - Java

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

Comparator is the way

Also See

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

SortedSet and Comparator. Comparator should honour the id field.

Solution 12 - Java

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

Solution 13 - Java

Your example:

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

You can also use a comparator:

list.sort(Comparator.comparingLong(CustomObject::getSomethingToCompare));

Just replace the comparingLong method, there are quite a few options, but it depends on what you want to pass on the "getSomethingToCompare".

This link may help too.

Solution 14 - Java

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

Solution 15 - Java

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMakkyView Question on Stackoverflow
Solution 1 - JavaKowserView Answer on Stackoverflow
Solution 2 - JavaAliaksei YatsauView Answer on Stackoverflow
Solution 3 - JavaShawn VaderView Answer on Stackoverflow
Solution 4 - JavaHunter McMillenView Answer on Stackoverflow
Solution 5 - JavaDwBView Answer on Stackoverflow
Solution 6 - JavaGerSuiView Answer on Stackoverflow
Solution 7 - JavaestaniView Answer on Stackoverflow
Solution 8 - JavajmjView Answer on Stackoverflow
Solution 9 - Javazw324View Answer on Stackoverflow
Solution 10 - JavaassyliasView Answer on Stackoverflow
Solution 11 - JavaAravind YarramView Answer on Stackoverflow
Solution 12 - Javauser7225794View Answer on Stackoverflow
Solution 13 - JavaYanMaxView Answer on Stackoverflow
Solution 14 - JavaShrikantView Answer on Stackoverflow
Solution 15 - Javauser13979347View Answer on Stackoverflow