Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting string value in a case-insensitive manner in Java 8

How do I sort string values in case-insensitive order in the following?

List<Employee> listofEmployees = Arrays.asList(     new Employee(1, "aaa", Arrays.asList(123, 345, 678)),     new Employee(1, "bbb", Arrays.asList(91011, 121314, 1516117)),     new Employee(2, "ccc", Arrays.asList(181920, 212223, 242526)),     new Employee(3, "ddd", Arrays.asList(272829, 303132, 333435)),     new Employee(4, "BBB", Arrays.asList(29, 332, 33)) ); 

I wrote like this:

listofEmployees.stream().sorted(Comparator.comparing(Employee::getName).reversed())         .forEach(s -> System.out.println(s.getName())); 

How do I pass a string case insensitive option here?

like image 688
Learn Hadoop Avatar asked Apr 13 '18 16:04

Learn Hadoop


People also ask

How do you sort a string case-insensitive?

An array can be sorted in case-insensitive order using the java. util. Arrays. sort() method.

How do you make a string case-insensitive in Java?

Java String equalsIgnoreCase() Method The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

What is case-insensitive order in Java?

Therefore, case sensitive order means, capital and small letters will be considered irrespective of case. The output would be − E, g, H, K, P, t, W. The following is our array − String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" }; Convert the above array to a List − List<String>list = Arrays.asList(arr);

How do I sort a string in Java 8?

We can also use Java 8 Stream for sorting a string. Java 8 provides a new method, String. chars() , which returns an IntStream (a stream of ints) representing an integer representation of characters in the String. After getting the IntStream , we sort it and collect each character in sorted order into a StringBuilder .


2 Answers

Try this

Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER) 
like image 190
Hadi J Avatar answered Oct 08 '22 12:10

Hadi J


As @Tree suggested in comments, one can use the java.text.Collator for a case-insensitive and locale-sensitive String comparison. The following shows how both case and accents could be ignored for US English:

Collator collator = Collator.getInstance(Locale.US); collator.setStrength(Collator.PRIMARY); listOfEmployees.sort(Comparator.comparing(Employee::getName, collator.reversed())); 

When collator strength is set to PRIMARY, then only PRIMARY differences are considered significant during comparison. Therefore, the following Strings are considered equivalent:

if (collator.compare("abc", "ABC") == 0) {     System.out.println("Strings are equivalent"); } 
like image 31
Oleksandr Pyrohov Avatar answered Oct 08 '22 11:10

Oleksandr Pyrohov