Sorted List Java Example
In this article, we will create a Java example on Sorted List. I will show how to sort a java.util.List
using methods of java.util.Collections
class.
1. SimpleSortExample
Create a Java class called SimpleSortExample
with the following source code.
SimpleSortExample.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.javacodegeeks.example; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SimpleSortExample { public static void main(String[] args) { List list = new ArrayList(); for ( int i= 0 ;i< 10 ;i++) { list.add(( int ) (Math.random() * 100 )); } System.out.println( "Initial List: " +list); Collections.sort(list); System.out.println( "Sorted List: " +list); } } |
Firstly I filled the list with random values, using (int) (Math.random() * 100)
to get integers between 0 and 100. Then, I print the unsorted and then the sorted version of this list, using Collections.sort()
. This is my output:
1 2 | Initial List: [81, 25, 13, 99, 56, 54, 99, 42, 95, 17] Sorted List: [13, 17, 25, 42, 54, 56, 81, 95, 99, 99] |
2. SortWithComparatorExample
There is another way of using Collections.sort
method, by passing a Comparator
as a parameter. SortWithComparatorExample
shows this:
SortWithComparatorExample.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package com.javacodegeeks.example; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortWithComparatorExample { public static void main(String[] args) { List list = new ArrayList(); for ( int i= 0 ;i< 10 ;i++) { list.add(( int ) (Math.random() * 100 )); } System.out.println( "Initial List: " +list); Collections.sort(list, new Comparator() { @Override public int compare(Integer i1, Integer i2) { return (i2.intValue() > i1.intValue()) ? 1 : - 1 ; } }); System.out.println( "Sorted List: " +list); } } |
I added a second parameter to Collections.sort
method in order to tell that method how to sort the list. This is performed by @Overriding
the compare method of the Comparator. My Comparator tells to the method that it should sort the list in the reversed order. My output is this:
1 2 | Initial List: [72, 64, 9, 84, 15, 8, 36, 72, 99, 3] Sorted List: [99, 84, 72, 72, 64, 36, 15, 9, 8, 3] |
3. ReverseSortExample
There is a simpler way to sort a list in the reversed order. Instead of creating your own Comparator
, Java gives you a pre-defined Comparator that you can pass as the second parameter of Collections.sort
method. Check out the code below:
ReverseSortExample.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 | package com.javacodegeeks.example; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReverseSortExample { public static void main(String[] args) { List list = new ArrayList(); for ( int i= 0 ;i< 10 ;i++) { list.add(( int ) (Math.random() * 100 )); } System.out.println( "Initial List: " +list); Collections.sort(list,Collections.reverseOrder()); System.out.println( "Sorted List: " +list); } } |
Instead of creating a new Comparator
, I used Collections.reverseOrder()
. This pre-defined Comparator does “the heavy work” of defining your own Comparator. The output is the same as the previous example:
1 2 | Initial List: [51, 74, 7, 15, 20, 65, 24, 23, 65, 81] Sorted List: [81, 74, 65, 65, 51, 24, 23, 20, 15, 7] |
4. Sort objects
Let us look at an example to sort objects. We defined a class Person as below. It implements Comparable and overrides the compareTo method.
Person.java
public class Person implements Comparable{ private String name; private int age; public Person(String strName, int iAge){ this.name = strName; this.age = iAge; } public String getName(){ return name; } public int getAge(){ return age; } public void setName(String strName){ this.name = strName; } public void setAge(int iAge){ this.age = iAge; } public String toString(){ return this.name; } // Compare method public int compareTo(Object obj){ return this.getName().compareTo(((Person) obj).getName()); } }
We will now try to sort Person objects using Collections.
SortedExample.java
import java.util.ArrayList; import java.util.List; import java.util.Collections; public class SortedExample { public static void main(String args[]){ Person p1 = new Person("Jack",30); Person p2 = new Person("Donald",29); Person p3 = new Person("Alvin",31); List personCollection = new ArrayList(); personCollection.add(p1); personCollection.add(p2); personCollection.add(p3); System.out.println("Before Sort :"+personCollection); // Using Collections Collections.sort(personCollection); System.out.println("After Sort :"+personCollection); } }
As you would notice, the above code would sort the objects based on the logic mentioned in compareTo
method in Person
class. The output would be as shown below:
Before Sort :[Jack, Donald, Alvin] After Sort :[Alvin, Donald, Jack]
5. Array.sort() vs Collection.sort()
Let us look at some differences between sort methods in Array and Collection.
Array.sort():
- Array.sort() sorts the specified array of objects into ascending order, according to the natural ordering of elements
- All elements must implement the Comparable interface and must be mutually comparable.
- The sort is guaranteed to be stable (i.e. equal elements will not be reordered as a result of this sort)
- The implementation is stable, adaptive, iterative mergesort that requires far fewer than O(nlog(n)) comparisons when the input array is partially sorted. It takes n comparisons for an input array that is nearly ordered.
- Uses dual-pivot Quicksort algorithm for primitive arrays.
Collections.sort():
- Collections.sort() sorts the specified list into ascending order, according to the natural ordering of elements
- All elements in the list must implement the Comparable interface and must be mutually comparable.
- The sort is guaranteed to be stable
6. Download the Source Code
You can download the full source code of this example here : Sorted List Java Example
Last updated on Jul. 20th, 2020