How to Use the Java Collections Sort Method

polymorphism in javaThe Java API has all the tools you need for manipulating and collecting data without having to write any sort of algorithms. The Java Collections framework is equipped with data structures that should work for virtually anything a Java programmer will ever need — whether you want to find something by name, keep a list that you can keep adding to, arrange a list of Strings alphabetically, or sort your pets by number of tricks they have learned. You can find all the necessary tools in Java API. The Collections classes and interfaces are in the java.util package.

New to Java Programming? Learn how to take advantage of available tools in Java API through a course in Udemy.

Java Collections is a group of classes and interfaces that provide easy and flexible ways to handle collection of objects. Collections classes have a special method sort(), which can be used for sorting items either in the natural order (alphanumeric), or a certain order you want. Not all Collections classes contain this method. The ArrayList class, for instance, does not have a sort method. Some important Collections classes in java API include: TreeSet, HashMap, LinkedList, HashSet and LinkedHashMap. List and Map are important Interfaces in the Collections framework. The sort() method is declared as static and can be directly called by the Collection Class. 

The Java Collections sort method is declared in two ways:

 1)     public static<T extends Comparable<? super T>> void sort (List<T> list)

OR

 2)     static<T> void sort(List<T> list, Comparator<? Super T> c)

Here ‘T’ stands for a generic type.  The method has no return type. The sort method along with several other methods in the Collections framework makes use of generics. Generics is an added feature in Java 5.0 and later versions. The main advantage of generics in java is that it lets you write type –safe collections. They allow a method or type to work on objects of different types while providing compile-time type safety.

Using the Java Collections Sort in List and LinkedList

You can sort objects in a List or LinkedList by using Collections.sort(). For the sort method to be able to sort objects in ways other than the natural order, the Comparable interface must be implemented. If you look at the declaration of the sort method above, you will notice that class extends Comparable . The term extend here actually means implements the interface Comparable. The Comparable interface is declared as follows:

public interface Comparable<T>
{
int compareTo(T obj);
}

The method in the comparable interface compares two objects and returns an integer value (a negative value, zero or a positive value).

Implications of the three returned values:

  • Positive – this means that the object running the method is greater than the object passed to the method as an argument.
  • Zero – this means that both objects are equal (although it does not necessarily mean they are the same object).
  • Negative – This means that the object passed to the method is greater than the object running the method.

Learn about the various Java Collections classes and Interfaces by taking a Java course in Udemy.com

Example code implementing Java Collections Sort

public class javasort
{
//main()
{
List<String> colors = new ArrayList<>(); // create arraylist and assign it to List
colors.add("red");  // add elements to arraylist
colors.add("green");
colors.add("yellow");
colors.add("blue");
colors.add("maroon");
Collections.sort(colors); // sort the string elements alphabetically
System.out.println("sorted list" + colors);//print sorted arraylist
}
}

OUTPUT:

Sorted list[blue, green, maroon, red, yellow]

In the above example, an ArrayList is assigned to a List instance variable.  List is an Interface and cannot be instantiated. ArrayList, on the other hand, does not have a sort method but the List Interface does. The ArrayList of String objects are sorted alphabetically since that is the natural order of String elements.

The Comparator and Comparable Interface in Java Collections Sort

Your class  can either implement the Comparator or the Comparable interface for sorting objects. The compare and compareTo methods are used to compare two objects.

You can use the compareTo() if you are looking to sort  java API Objects (objects you did not create) like Integer or String — compareTo() provides sorting in natural order. You can use the compare() for comparing two object instances (mostly custom objects) with arbitrary fields.

In the above Java code Example 1, sorting String objects was simple. You can intuitively tell that sorting the String elements alphabetically is the natural order and Collections.sort() does just that. But what if we want items arranged in a certain order or by a specific field?  That is where the Comparable interface comes in. Comparable is used for customized sorting on objects you created, such as, books, songlist, users or cars. It compares two object by using the compareTo(Object obj).

Sorting Custom Objects

Sorting objects such as String objects is pretty straight forward. You can directly use Collections.sort(ArrayList list).

Let’s say you have a JukeBox class that has a list of songs. Every track has three pieces of information about the song: the title, the artist and the rating. The above method will never know how to sort the tracks. The compare() will help you sort the list either by title, artist or rating according to your specification.

Learn the various sorting techniques in Java with a course in Udemy.com

The following code example illustrates the use java collections sort to arrange a song list by title, artist or rating. The rating forms as the natural order in the following example —sorting tracks based on popularity.

class Song implements Comparable<Song>
{
String title;
String artist;
int rating;

public static class SortByTitle implements Comparator //inner class to sort by title
{
public int compare(Song track1, Song track2)
{
return track1.title.compareTo(track2.title);
}
}
public static class SortByArtist implements Comparator //inner class to sort by artist
{
public  int compare(Song track1, Song track2)
{
return track1.artist.compareTo(track2.artist);
}
}
public Song(String t, String a, int r) // Song constructor that takes in song details
{
this.title = t;
this.artist = a;
this.rating = r;
}
public String getTitle(){return title;}
public void setTitle(String s1){ this.title = s1;}
public String getArtist(){return artist;}
public void setArtist(String s1){this.artist = s1;}
public int compareTo(Song o)
{
return this.rating > o.rating ? 1 : (this.rating < o.rating ? -1 : 0);
}
//override toString to print sorting by rating
public String toString()
{
return String.valueOf(rating);
}
}

The JukeBox class using Collections.sort

public class JukeBox
{
public static void main(String[] arg)
{
Song S1 = new Song("Face to Face", "Daft Punk", 4);
Song S2 = new Song("Chandelier", "Sia", 5);
Song S3 = new Song("Use Somebody", "Kings Of Leon",3);
Song S4 = new Song("Be Mine"," Ellie Goulding", 2);
List<Song> songList = new ArrayList<Song>();
songList.add(S1);
songList.add(S2);
songList.add(S3);
songList.add(S4);
System.out.println(" UnSorted List: " + songList);
Collections.sort(songList);
System.out.println("Sorted List: " + songList);
Collections.sort(songList, new Song.SortByTitle());
System.out.println(" Tracks sorted by Title " + songList);
Collections.sort(songList, new Song.SortByArtist());
System.out.println(" Tracks sorted by Artist " + songList);
}
}