在 Java 8 中以不区分大小写的方式对字符串值进行排序

2022-09-01 01:42:42

如何在下面按不区分大小写的顺序对字符串值进行排序?

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))
);

我这样写道:

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

如何在此处传递字符串大小写不敏感的选项?


答案 1

试试这个

Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)

答案 2

正如注释中@Tree建议的那样,可以使用java.text.Collator进行不区分大小写和区分区域设置的比较。下面显示了如何忽略美国英语的大小写和重音符号:String

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

当归类器强度设置为 时,在比较过程中只考虑显著差异。因此,以下字符串被视为等效项:PRIMARYPRIMARY

if (collator.compare("abc", "ABC") == 0) {
    System.out.println("Strings are equivalent");
}

推荐