Java ArrayList sort() Method Example

ArrayListsort() method sorts the list according to the order induced by the specifiedComparator instance. All elements in the list must be mutually comparable.

Java ArrayList sort() Method Example

importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;// Sort an ArrayList using Collections.sort() method.// Sort an ArrayList using ArrayList.sort() method.// Sort an ArrayList of user defined objects with a custom comparator.publicclassArrayListSortExample {publicstaticvoidmain(String[]args) {List<String> names=newArrayList<>();        names.add("Tony");        names.add("Tom");        names.add("Johnson");        names.add("John");        names.add("Ramesh");        names.add("Sanjay");System.out.println("Names :"+ names);// Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.        names.sort(newComparator<String>() {@Overridepublicintcompare(Stringname1,Stringname2) {return name1.compareTo(name2);            }        });// The above `sort()` method call can also be written simply using lambda expression        names.sort((name1, name2)-> name1.compareTo(name2));// Following is an even more concise solution        names.sort(Comparator.naturalOrder());System.out.println("Sorted Names :"+ names);    }}
Output:
Names : [Tony, Tom, Johnson, John, Ramesh, Sanjay]Sorted Names : [John, Johnson, Ramesh, Sanjay, Tom, Tony]

Reference

Java ArrayList Source Code Examples


Comments