如果名字重复且姓氏为空,请从列表中删除客户

时间:2019-03-03 17:01:04

标签: java java-8 java-stream

我想基于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保留customer1customer3 删除customer2,因为firstNamecustomer1重复且lastName为空

1 个答案:

答案 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()));