Sorting irrespective of case in java

sorting irrespective of case in java (Last Updated On: August 11, 2016)

Sorting irrespective of case in java:

In Java if you want to sort the elements then you can use treeset. Set will not allow duplicates, but if you have the same element in both small and upper case then it will consider that as separate elements.

 

Sorting respective of case:


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

public class Sorting {

/**
* @param args
*/
public static void main(String[] args) {
Set<String> mySet = new TreeSet<String>();
mySet.add("Vizag");
mySet.add("arcot");
mySet.add("Vellore");
mySet.add("delhi");
mySet.add("Bangalore");
mySet.add("chennai");
for (String string : mySet) {
System.out.println(string);
}

}

}

 

Output:


Arcot
Bangalore
Vellore
Vizag
arcot
chennai
delhi

 

here,┬ásorting happended only with capital letters first then small letter sorting happended. If you want to sorting irrespective of case then use “CASE_INSENSITIVE_ORDER”.

 

Sorting irrespective of case:

If we add the “String.CASE_INSENSITIVE_ORDER” then it will remove the duplicates and sort in combined caps/small order.


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

public class Sorting {

/**
* @param args
*/
public static void main(String[] args) {
Set<String> mySet = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

mySet.add("Vizag");
mySet.add("arcot");
mySet.add("Vellore");
mySet.add("delhi");
mySet.add("Bangalore");
mySet.add("chennai");
mySet.add("Arcot");
for (String string : mySet) {
System.out.println(string);
}

}

}

 

Output:


arcot
Bangalore
chennai
delhi
Vellore
Vizag

 

Java Recommended Books – Collections:

 

 

Feel free to share your comments/feedbacks/suggestions….

 

 

203 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *