Java Set Sort

In this tutorial, we will learn about java collection set sorting along with working examples including user-defined or custom sorting.

Set sort

In Java, Set interface does not any have any direct sort method unlike in the list, to allow this we have an inbuilt SortedSet interface and this interface is implemented by the TreeSet class. If we create TreeSet object directly by specifying Comparator implemented class it will follow the sort order while adding elements into the TreeSet and no need to call or invoke sort method explicitly.

In case of other implementation classes of Set interface like HashSet and LinkedHashSet, there is no direct sorting technique is available instead of direct sorting, we can achieve it by adding the elements of HashSet or LinkedHashSet into the TreeSet.

Set sort for HashSet elements:

To sort HashSet objects, we need to pass HashSet objects to TreeSet constructor to achieve sorting.

HashSet<String> hashSet = new HashSet<>();
hashSet.add("One");
hashSet.add("Two");
hashSet.add("Three");
hashSet.add("Four");
hashSet.add("Five");
TreeSet<String> treeSet = new TreeSet<>(hashSet);
System.out.println(treeSet);

And same should be followed for LinkedHashSet also. As shown below,

Set sort for LinkedHashSet elements:

And same should be followed for LinkedHashSet also. As shown below,

LinkedHashSet<String> linkedhashSet = new LinkedHashSet<>();
linkedhashSet.add("Zebra");
linkedhashSet.add("Monkey");
linkedhashSet.add("Animal");
linkedhashSet.add("Peacock");
linkedhashSet.add("Frog");
TreeSet<String> treeSet = new TreeSet<>(linkedhashSet);
System.out.println(treeSet);

If we do not specify any Comparator while creating TreeSet, then it will follow the element Class Comparable interface implementation, in case Comparable interface is not implemented by element class this will lead to ClassCastException during Runtime.

Set sort example with in-built class:

CopiedCopy Code
import java.util.Collections;
import java.util.TreeSet;
public class TreeSetNaturalSortExample {
	public static void main(String[] args) {
		//Without any Comparator TreeSet object is created
		TreeSet<String> treeSet = new TreeSet<>();
		//Adding elements of type String 
		treeSet.add("One");
		treeSet.add("Two");
		treeSet.add("Three");
		treeSet.add("Four");
		treeSet.add("Five");
		//Printing elements and it will follow natural sort
		System.out.println(treeSet);
	}
}

Output :

[Five, Four, One, Three, Two]

Set sort example with custom class:

In this example, we will sort Set elements with the custom sorting or user-defined sorting.

CopiedCopy Code
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetCustomSort {
	public static void main(String[] args) {
		//Passing Comparator to TreeSet class to sort songs in reverse order
		TreeSet<Albums> treeSet = new TreeSet<>(new Comparator<Albums>() {
			@Override
			public int compare(Albums o1, Albums o2) {
				// o2 object is compared with o1, it will reverse natural order
				return o2.song.compareTo(o1.song);
			}
		});
		Albums albm1 = new Albums("Abilene", "Bluegrass");
		Albums albm2 = new Albums("Above And Beyond", "Bluegrass");
		Albums albm3 = new Albums("Acadian Driftwood", "Roots");
		Albums albm4 = new Albums("Acquiesce", "Pop");
		treeSet.add(albm1);
		treeSet.add(albm2);
		treeSet.add(albm3);
		treeSet.add(albm4);
		//In Comparator we used custom compare logic to reverse natural order
		System.out.println(treeSet);
	}
	static class Albums {
		public String song;
		public String genre;
		public Albums(String song, String albumName) {
			this.song = song;
			this.genre = albumName;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((genre == null) ? 0 : genre.hashCode());
			result = prime * result + ((song == null) ? 0 : song.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			Albums other = (Albums) obj;
			if (genre.equals(other.genre) && song.equals(other.song))
				return true;
			return false;
		}
		@Override
		public String toString() {
			return "Albums [song=" + song + ", genre=" + genre + "]";
		}
	}
}

Output :

[Albums [song=Acquiesce, genre=Pop], Albums [song=Acadian Driftwood, genre=Roots], Albums [song=Above And Beyond, genre=Bluegrass], Albums [song=Abilene, genre=Bluegrass]]

Conclusion :

In this tutorial, we have covered about how to sort Set elements along with the working examples of it including custom sort.