我想基于first name
为空的last name
从对象列表中删除重复项
我们可以在Java 8中做到吗?
public void test() {
List<Customer> customers = new ArrayList<>();
Customer customer1 = new Customer();
customer1.setFirstName("Abc");
customer1.setLastName("def");
Customer customer2 = new Customer();
customer2.setFirstName("Abc");
customer2.setLastName(null);
Customer customer3 = new Customer();
customer3.setFirstName("toms");
customer3.setLastName(null);
customers.add(customer1);
customers.add(customer2);
customers.add(customer3);
customers = customers.stream().filter(c -> {
return c.getLastName() != null;
}).collect(Collectors.toList());
System.out.println(customers);
}
这是我的Customer.class
private class Customer {
String firstName;
String lastName;
//get set
}
我不想删除customer3
,因为它的偶数lastName
为空但不能重复
customers
保留customer1
和customer3
删除customer2
,因为firstName
与customer1
重复且lastName
为空
答案 0 :(得分:0)
我分两步进行,首先将所有具有全名(因此可能有重复)的客户收集到名字列表中,然后从原始列表中删除我的收集中存在且姓氏为空的所有客户列表
List<String> properNames = customers.stream()
.filter(c -> c.getLastName() != null)
.map(Customer::getFirstName)
.collect(Collectors.toList());
customers.removeIf(c -> c.getLastName() == null
&& properNames.contains(c.getFirstName()));