Sorting Collection of String, StringBuffer and StringBuilder in Java

In this article, we will discuss how to sort collection of,

  1. String
  2. StringBuffer
  3. StringBuilder

In Collection framework hierarchy, below classes sorts value/objects stored by-default in natural sorting-order,

  1. TreeSet
  2. Treemap

Note: – for our sorting examples, we will use TreeSet class to store value/objects so that it gets sorted while storing/adding itself

 

1. Sorting Collection of String:

Signature of String class:

public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

SortingString.java

package in.bench.resources.sorting.string;

import java.util.Set;
import java.util.TreeSet;

public class SortingString {

	public static void main(String[] args) {

		// creating TreeSet object using Set reference-type
		Set<String> string = new TreeSet<String>();

		// adding/storing String value/objects
		string.add("Thuppakki");
		string.add("Kaththi");
		string.add("Bairavaa");
		string.add("Mersal");
		string.add("Sarkar");

		// displaying/printing String value/objects
		System.out.println(string);
	}
}

Output:

[Bairavaa, Kaththi, Mersal, Sarkar, Thuppakki]

Explanation:

  • When String value/objects are stored/added to TreeSet class, then it stores values in natural sorting-order i.e.; value/objects are sorted in alphabetical order
  • Reason: String implements java.lang.Comparable interface which helps to sort among one-another while storing/adding value/objects itself in TreeSet
  • As you can see from above program display/output, String value/objects are printed in the natural alphabetic order

 

2. Sorting Collection of StringBuffer:

Signature of StringBuffer class:

public final class StringBuffer
extends Object
implements Serializable, CharSequence

SortingStringBuffer.java

package in.bench.resources.sorting.string;

import java.util.Set;
import java.util.TreeSet;

public class SortingStringBuffer {

	public static void main(String[] args) {

		// creating TreeSet object using Set reference-type
		Set<StringBuffer> strBuffer = new TreeSet<StringBuffer>();

		// adding/storing String value/objects
		strBuffer.add(new StringBuffer("Thuppakki"));
		strBuffer.add(new StringBuffer("Kaththi"));
		strBuffer.add(new StringBuffer("Bairavaa"));
		strBuffer.add(new StringBuffer("Mersal"));
		strBuffer.add(new StringBuffer("Sarkar"));

		// displaying/printing String value/objects
		System.out.println(strBuffer);
	}
}

Output:

Explanation:

  • When StringBuffer value/objects are stored/added to TreeSet class, then no error is thrown during compilation
  • But at runtime or during execution of program, a java.lang.ClassCastException is thrown as shown in the output console
  • Error: what ClassCastException describe in the above screen-capture  is that “java.lang.StringBuffer cannot be cast to java.lang.Comparable
  • Reason: StringBuffer do not implements java.lang.Comparable interface, as shown StringBuffer signature above
  • While storing/adding StringBuffer value/objects to TreeSet class, it doesn’t understand on what basis these value/objects need to be sorted
  • So, we need to add/store only those values to TreeSet class, which is comparable among each other
  • Therefore, we must define explicit custom comparator for StringBuffer class and pass it as constructor-argument, as described in the following section

2.1 StringBuffer Comparator

  • First, we need define StringBuffer comparator by implementing java.util.Comparator interface and providing logic for compare() method
  • Here, we compared StringBuffer objects using compareTo() method of java.lang.Comparable interface, after converting StringBuffer object into String object
  • Thereby, String comparison yields sorting in alphabetically natural-order
  • Note: just interchanging sbf1 with sbf2 will yield results in reverse-order

StringBufferCustomComparator.java

package in.bench.resources.sorting.string;

import java.util.Comparator;

public class StringBufferCustomComparator 
						implements Comparator<StringBuffer> {

	@Override
	public int compare(StringBuffer sbf1, StringBuffer sbf2) {
		return sbf1.toString().compareTo(sbf2.toString()); 
	}
}

SortingStringBufferUsingCustomComparator.java

package in.bench.resources.sorting.string;

import java.util.Set;
import java.util.TreeSet;

public class SortingStringBufferUsingCustomComparator {

	public static void main(String[] args) {

		// creating TreeSet object using Set reference-type
		// using customer-comparator as constructor-argument
		Set<StringBuffer> strBuffer = new TreeSet<StringBuffer>(
				new StringBufferCustomComparator());

		// adding/storing String value/objects
		strBuffer.add(new StringBuffer("Thuppakki"));
		strBuffer.add(new StringBuffer("Kaththi"));
		strBuffer.add(new StringBuffer("Bairavaa"));
		strBuffer.add(new StringBuffer("Mersal"));
		strBuffer.add(new StringBuffer("Sarkar"));

		// displaying/printing String value/objects
		System.out.println(strBuffer);
	}
}

Output:

[Bairavaa, Kaththi, Mersal, Sarkar, Thuppakki]

 

3. Sorting Collection of StringBuilder:  

Signature of StringBuilder class:

public final class StringBuilder
extends Object
implements Serializable, CharSequence

Runtime-exception for StringBuilder class:

Explanation:

  • StringBuilder class too do not implements java.lang.Comparable interface, as shown in StringBuilder class signature above
  • A runtime exception is thrown during execution of program, as shown in the above screen-capture
  • Therefore, we must provide custom comparator similar to StringBuffer as explained in the above point 2
  • So, we will provide custom comparator implementing java.util.Comparator interface and overriding compare() method
  • And providing logic to sort StringBuilder value/objects in reverse-order

StringBuilderCustomComparator.java

package in.bench.resources.sorting.string;

import java.util.Comparator;

public class StringBuilderCustomComparator  
						implements Comparator<StringBuilder> {

	@Override
	public int compare(StringBuilder sbd1, StringBuilder sbd2) {
		return sbd2.toString().compareTo(sbd1.toString()); 
	}
}

SortingStringBuilderUsingCustomComparator.java

package in.bench.resources.sorting.string;

import java.util.Set;
import java.util.TreeSet;

public class SortingStringBuilderUsingCustomComparator {

	public static void main(String[] args) {

		// creating TreeSet object using Set reference-type
		// using customer-comparator as constructor-argument
		Set<StringBuilder> strBuffer = new TreeSet<StringBuilder>(
				new StringBuilderCustomComparator());

		// adding/storing String value/objects
		strBuffer.add(new StringBuilder("Thuppakki"));
		strBuffer.add(new StringBuilder("Kaththi"));
		strBuffer.add(new StringBuilder("Bairavaa"));
		strBuffer.add(new StringBuilder("Mersal"));
		strBuffer.add(new StringBuilder("Sarkar"));

		// displaying/printing String value/objects
		System.out.println(strBuffer);
	}
}

Output:

[Thuppakki, Sarkar, Mersal, Kaththi, Bairavaa]

 

Conclusion:

  • To conclude, we must keep-in-mind that while sorting any item/objects using TreeSet, then those value/objects must be stored which are comparable among each-other
  • Otherwise, we must provide explicit custom comparator
  • Since String class implements java.lang.Comparable interface, therefore it isn’t required to provide any custom comparator
  • Whereas for StringBuffer/StringBuilder which do not implements java.lang.Comparable interface like String class, therefore it is must to provide to custom-logic to sort by implementing java.util.Comparator interface and overriding compare() method

 

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

References:

 

Happy Coding !!
Happy Learning !!

How to sort Vector using Collections.sort() in Java
How to remove an entry from HashMap by comparing keys in Java 8