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 the 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 Users and sort them by there Name (type String).
- The user class will have two fields userName and phone number.
- In order to be able to use the sort method from the collections class, we have to implement the comparable interface.
The 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:
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
Note : Collections.reverseOrder() => lets you sort in reverse natural order
When to use Comparable:
- When we need to sort collection on the basis of a single element