How do we sort in Java?

  • We can go the traditional way by implementing Bubble Sort or Merge Sort etc
  • We can use Java APIs

In this post we will focus on Sorting using Java APIs

Sort List of Integer

Given an Integer List say [7, 4, 2, 9, 5, 2, 3] to sort
We will use Java Collection Framework to do this.

Points to Note:

  • List<Integer> => The Integer class wraps a value of the primitive type int in an object.
  • Collections.sort(ints) =>
    It sorts elements in order induced by the specified Comparator or else in element’s natural ordering. Sort technique used by Collections is mergesort.

Sort List of Object

  • Let’s create a list of User and sort them by there Name (type String).
  • The user class will have two fields userName and phoneNo.
  • In order to be able to use the sort method from the collections class we have to implement the comparable interface.

User.java

 

public class UserName implements Comparable<UserName>{
    private String userName;
    private String phoneNo;

    // getter setters
}

Compiler shows an Error “The type UserName must implement the inherited abstract method Comparable<UserName>.compareTo(UserName)

This means that in order to implement Comparable we have to implement compareTo method of Comparable interface which goes like this:

public int compareTo(UserName u) {
    int lastCmp = userName.compareTo(u.getUserName());
    return (lastCmp != 0 ? lastCmp : userName.compareTo(u.getUserName()));
}

By implementing compareTo we are defining the element by which User Object must be sorted in element’s natural ordering and it can only be one. This method returns an int

  • 0 : if objects are equal
  • -1 : if less than
  • 1 : if greater than

Example:

public static void main(String[] args) {

    User name[] = {
        new User("Aashish", 12),
        new User("Suman", 12),
        new User("Naveen", 34),
        new User("Ashish", 10),
        new User("Dheepan", 10),
        new User("Satish", 26)
    };

    // Sort by natural order
    List names = Arrays.asList(name);
    Collections.sort(names);
    System.out.println(names);

    // Sort by reverse natural order
    Collections.sort(names, Collections.reverseOrder());
    System.out.println("Sort by reverse natural order");
    System.out.println(names);
}

Output:

    [Aashish 12, Ashish 10, Dheepan 10, Naveen 34, Satish 26, Suman 12]
Sort by reverse natural order
    [Suman 12, Satish 26, Naveen 34, Dheepan 10, Ashish 10, Aashish 12]

Note : Collections.reverseOrder() => lets you sort in reverse natural order

When to use Comparable:

  • When we need to sort collection on the basis of single element
Categories: JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.