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

前端 未结 6 892
春和景丽
春和景丽 2021-01-01 08:57

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

List listofEmployees = Arrays.asList(
    new Employee(1, \"aaa\", Ar         


        
相关标签:
6条回答
  • 2021-01-01 09:39

    This is one of many ways:

    listofEmployees.stream()
        .sorted((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()))
        .forEach(s -> System.out.println(s.getName()));
    
    0 讨论(0)
  • 2021-01-01 09:43

    You can specify it as the second argument to ignore cases:

    Comparator.comparing(Employee::getName, String::compareToIgnoreCase).reversed()
    
    0 讨论(0)
  • 2021-01-01 09:48

    It looks like there is a Comparator that orders String objects as by compareToIgnoreCase, you can read the documentation here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER

    0 讨论(0)
  • 2021-01-01 09:50

    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");
    }
    
    0 讨论(0)
  • 2021-01-01 09:55

    You can lowercase or uppercase it like this:

    listofEmployees.stream()
                   .sorted(Comparator.comparing((Employee e) -> e.getName()
                                     .toLowerCase()) // or toUpperCase
                                     .reversed())
                   .forEach(s -> System.out.println(s.getName()));
    
    0 讨论(0)
  • 2021-01-01 09:56

    Try this

    Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
    
    0 讨论(0)
提交回复
热议问题