Sorting a collection of objects can be done in two ways:
- By implementing Comparable (Natural Order) e.g. Strings are sorted ASCIIbetically. meaning B comes before A and 10 is before 2.
- By implementing Comparator (Custom order) and it can be in any order.
- Using Collections.sort() method of Collections utility class.
Read more about Comparable and Comparator
For sorted Collection we can use below collections:
- TreeSet
- TreeMap
In case of String, sorting will be done automatically in natural order.
Java
public final class String
extends Object
implements Serializable,
Comparable, CharSequence
|
Output:
[Harish, Raja, Ram, Sohan]
Java
public final class StringBuffer
extends Object
implements Serializable,
CharSequence
|
Output
[Harish, Raja, Ram, Sohan]
String class implements Comparable interface whereas StringBuffer and StringBuilder classes do not implement Comparable interface. See below signatures of String, StringBuffer and StringBuilder classes:
Java
public final class StringBuilder
extends Object
implements Serializable,
CharSequence
|
Java
// Java program to demonstrate sorting // of StringBuffer objects using Comparator // interface. import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Test implements Comparator<StringBuffer> {
@Override public int compare(StringBuffer s1, StringBuffer s2)
{
return s1.toString().compareTo(s2.toString());
}
public static void main(String[] args)
{
Set<StringBuffer> str = new TreeSet<>( new Test());
str.add( new StringBuffer( "Sohan" ));
str.add( new StringBuffer( "Raja" ));
str.add( new StringBuffer( "Harish" ));
str.add( new StringBuffer( "Ram" ));
System.out.println(str);
}
} |
Java
There are many ways of sorting StringBuffer, StringBuilder classes. Some of the ways are given below:
- By implementing Comparator interface
- By converting StringBuffer to String using StringBuffer.toString() method
Java
// Java program to demonstrate sorting // of StringBuffer objects using Comparator // interface. import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Test implements Comparator<StringBuffer> {
@Override public int compare(StringBuffer s1, StringBuffer s2)
{
return s1.toString().compareTo(s2.toString());
}
public static void main(String[] args)
{
Set<StringBuffer> str = new TreeSet<>( new Test());
str.add( new StringBuffer( "Sohan" ));
str.add( new StringBuffer( "Raja" ));
str.add( new StringBuffer( "Harish" ));
str.add( new StringBuffer( "Ram" ));
System.out.println(str);
}
} |
Output:
[Harish, Raja, Ram, Sohan]