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.
For sorted Collection we can use below collections:
In case of String, sorting will be done automatically in natural order.
[Harish, Raja, Ram, Sohan]
In case of StringBuffer or StringBuilder an exception will be thrown.
Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at Test.main(Test.java:11)
String class implements Comparable interface whereas StringBuffer and StringBuilder classes do not implement Comparable interface. See below signatures of String, StringBuffer and StringBuilder classes:
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
[Harish, Raja, Ram, Sohan]
This article is contributed by Sajid Ali Khan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- equals() on String and StringBuffer objects in Java
- String vs StringBuilder vs StringBuffer in Java
- Matcher appendReplacement(StringBuffer, String) method in Java with Examples
- A Java Random and StringBuffer Puzzle
- Difference Between StringBuffer and StringBuilder in Java
- StringBuffer class in Java
- StringBuffer insert() in Java
- StringBuffer deleteCharAt() Method in Java with Examples
- StringBuffer appendCodePoint() Method in Java with Examples
- StringBuffer delete() Method in Java with Examples
- StringBuffer replace() Method in Java with Examples
- StringBuffer reverse() Method in Java with Examples
- StringBuffer append() Method in Java with Examples
- StringBuffer setLength() in Java with Examples
- StringBuffer subSequence() in Java with Examples
- StringBuffer codePointCount() method in Java with Examples
- StringBuffer codePointBefore() method in Java with Examples
- StringBuffer trimToSize() method in Java with Examples
- StringBuffer toString() method in Java with Examples
- StringBuffer codePointAt() method in Java with Examples