根据不同大小写字符串 属性 in Java 8 从对象列表中删除重复项
Remove duplicates from a list of objects based on different case String property in Java 8
如何根据 Java 8 中的 "String" 属性 从对象列表中删除重复项?
我只能找到 Int 或 long 属性 的代码,但当字符串大小写不同并获得唯一列表时无法找到字符串比较。
以下是我正在尝试实现的程序。
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
是不同的字符串,不区分大小写Comparator
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
如何根据 Java 8 中的 "String" 属性 从对象列表中删除重复项? 我只能找到 Int 或 long 属性 的代码,但当字符串大小写不同并获得唯一列表时无法找到字符串比较。
以下是我正在尝试实现的程序。
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
是不同的字符串,不区分大小写Comparator
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)