Monday, September 9, 2019

How to Sort ArrayList in Java

In ArrayList elements are added in sequential order and while displaying the elements by iterating an arraylist that same default ordering will be used. Sometimes you may have a requirement to sort an ArrayList in Java in ascending or descending order. In this post we'll see how to sort an ArrayList of Strings, Integers or Dates in Java.


Options for sorting a List

You can sort an ArrayList using-

  1. sort() method of the List interface Java 8 onward. Note that sort() method is implemented as a default interface method in List interface.
    • default void sort(Comparator<? super E> c)- Sorts this list according to the order induced by the specified Comparator. If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.
  2. Using Collections.sort() method. There are two overloaded versions of sort method and according to Java docs their description is-
    • public static <T extends Comparable<? super T>> void sort(List<T> list)- Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

    • public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).
  3. Using sorted method of the Java Stream API. There are two overloaded variants of the sorted method.
    • sorted()- Returns a stream consisting of the elements of this stream, sorted according to natural order.
    • sorted(Comparator<? super T> comparator)- Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

Sorting ArrayList of strings using sort() method of List

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // Passing null so natural ordering is used
    cityList.sort(null);
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using naturalOrder method to sort in natural order
    cityList.sort(Comparator.naturalOrder());
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using reverseOrder method to impose reverse of natural ordering
    cityList.sort(Comparator.reverseOrder());
    System.out.println("List sorted in reverse" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse[Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Using Collections.sort() method to sort ArrayList

To sort an ArrayList of strings according to the natural ordering of its elements we can use the first of the two sort methods.

Collections.sort(List<T> list)
public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    // sorting the list
    Collections.sort(cityList);
    System.out.println("List sorted using natural ordering" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]

As you can see you just need to pass the ArrayList to sort method. Collections.sort will work in this case because String class implements Comparable interface and provides implementation for the method compareTo(String anotherString).

Same way Integer class or Date class also implements Comparable interface so list of integers (or dates) can also be sorted in natural order by using sort() method of the Collections class or by using sort() method of the List interface. In fact Java docs give a list of all the classes that implements comparable interface thus can be used with the sort method to sort the elements in the natural order.

Classes Implementing Comparable

Following is the list of classes that already implement Comparable interface in Java. Thus the ArrayList storing obejcts of any of these classes can be sorted in its natural ordering by passing the list to sort() method.

Class Natural Ordering
Byte Signed numerical
Character Unsigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

Sorting an ArrayList of strings in descending order

Collections.sort() method always sorts ArrayList of strings in ascending order. For sorting an ArrayList in descending order you need to use the second sort method which takes two parameters. First is the list that has to be sorted and second a comparator class that can be used to allow precise control over the sort order.
For sorting an ArrayList in descending order there are two options,

  • Use method reverseOrder() provided by Collections class itself

    General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  • Using a custom comparator.

Sorting ArrayList in descending order using reverseOrder method

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, Collections.reverseOrder());
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Sorting ArrayList in descending order using custom Comparator

Internally reverseOrder method calls a Comparator class to sort the list in reverse order. We can do it ourselves too by writing our own comparator class.

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, (String a, String b)->  b.compareTo(a));
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Note that Comparator is implemented as a lambda expression here.

Sorting Java ArrayList using sorted method of the Java Stream

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    List<String> tempList = cityList.stream().sorted().collect(Collectors.toList());
    System.out.println("List sorted in natural order- " + tempList);
    tempList = cityList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    System.out.println("List sorted in reverse order- " + tempList);
  }
}

Output

List sorted in natural order- [Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

That's all for this topic How to Sort ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Join Lists in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Difference Between Comparable and Comparator in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How to Iterate a HashMap of ArrayLists of String in Java
  3. static import in Java
  4. interface static methods in Java 8
  5. Method reference in Java 8
  6. Count Total Number of Times Each Character Appears in a String - Java Program
  7. Java ThreadLocal Class With Examples
  8. Try-With-Resources in Java With Examples

2 comments:

  1. awesome explanation of all topis ..looking more for jsp servlet mvc

    ReplyDelete