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?
An array can be sorted in case-insensitive order using the java. util. Arrays. sort() method.
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.
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);
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 .
Try this
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With