如何根据Java 8中的" String"属性列表从对象列表中删除重复项?我只能找到INT或长属性的代码,但在字符串为差异情况并获取唯一列表时无法找到字符串比较。
以下是我要实现的程序。
public class Diggu {
class Employee{
private int id;
private String name;
public Employee(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public void ra(){
List<Employee> employee = Arrays.asList(new Employee(1, "John"), new Employee(3, "JOHN"), new Employee(2, "BOB"));
System.out.println(""+ employee.size());
List<Employee> unique = employee.stream()
.collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparing(Employee::getName))),
ArrayList::new));
System.out.println(""+ unique.size());
}
public static void main(String[] args) {
new Diggu().ra();
}
}
结果:
run:
3
3
BUILD SUCCESSFUL (total time: 2 seconds)
在哪里应该是3和2
John
和 JOHN
是不同的字符串,请使用case不敏感的Comparator
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)