如何根据Java 8中的“String”属性从对象列表中删除重复项? 我只能找到Int或long属性的代码,但是当string是不同的情况并获得唯一列表时,无法找到字符串比较。
以下是我想要实现的计划。
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
答案 0 :(得分:1)
JOHN
和Comparator
是不同的字符串,使用不区分大小写的 Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
// Given an array of elements (here just Ints):
let array = (0..<1000).map { _ in Int(arc4random_uniform(100)) }
// Sort it:
let sorted = array.sorted()
// Define an empty result (array of elements) which is a variable
// and which gets modified in the subsequent reduce function:
var unique: [Int] = []
// A tailored reduce which depends on a sorted array and appends
// to the result IFF that element is not the last in result:
let result = sorted.reduce(into: unique) { (result, element) in
if let last = result.last, last == element {
} else {
result.append(element)
}
}