过滤对象中的子列表并返回Java 8

时间:2020-08-17 05:41:35

标签: java java-8 java-stream

我需要一个雇员对象,该对象的地址应从该对象下面开始,其引脚为40001。

    Employee eObj= new Employee(1,"abc",10001,
                    Arrays.asList(new Address("ad1","ad2","tel","40001"),new Address("ad1","ad2","tel1","40002")));

//需要帮助以编写下面的逻辑

Employee filteredEobj ={Logic}

//期望的响应

new Employee(1,"abc",10001,Arrays.asList(new Address("ad1","ad2","tel","40001"));
How can we achieve this using java 8?

3 个答案:

答案 0 :(得分:2)

假设您具有相应的吸气剂,并要求提供流变体:

Address address = eObj.getAddresses()
    .stream()
    .map(Employee::getAddress)
    .anyMatch(a -> a.getPostCode().equals("40001"))
    .orThrow(); // Whatever logic you want in case not found

Employee filteredEObj = new Employee(eObj.getFoo(), eObj.getBar() , eObj.getBaz(), List.of(address)); // i dont really know what those parameters are supposed to be

传统循环

还有更传统的方法:

Address matchAddress = null;
for (Address address : eObj.getAddresses()) {
    if (address.getPostCode().equals("40001")) {
        matchAddress = address;
        break;
    }
}

if (matchAddress == null) {
    // TODO case not found ...
}

Employee filteredEObj = new Employee(eObj.getFoo(), eObj.getBar() , eObj.getBaz(), List.of(matchAddress));

只是流

最后是一路使用流的变体:

Employee filteredEObj = eObj.getAddresses()
    .stream()
    .map(Employee::getAddress)
    .filter(a -> a.getPostCode().equals("40001"))
    .limit(1)
    .map(a -> new Employee(eObj.getFoo(), eObj.getBar() , eObj.getBaz(), List.of(a));
    .findAny()
    .orThrow(); // Whatever logic you want in case not found

多个匹配项

如果您对所有匹配的地址感兴趣,而不仅仅是一个,您可以简单地收集到一个列表中。例如:

List<Address> addresses = eObj.getAddresses()
    .stream()
    .map(Employee::getAddress)
    .filter(a -> a.getPostCode().equals("40001"))
    .collect(Collectors.toList());

// List is empty in case no matches

Employee filteredEObj = new Employee(eObj.getFoo(), eObj.getBar() , eObj.getBaz(), addresses);

答案 1 :(得分:1)

您可以先过滤地址,然后使用新地址的数据创建员工。

List<Address> filterdAddresses = eObj.getAdresses()
                            .stream()
                            .filter(a -> a.getPin().equals("40001"))
                            .collect(Collectors.toList());

Employee filteredEObj = new Employee(eObj.getId(), eObj.getName() , eObj.getEmpId(), filterdAddresses);

注意:我假设Employee的使用者正在学习,因为您尚未显示课程。

答案 2 :(得分:0)

List<Employee> employees = empObjs.stream()
                                   .filter(e -> ("40001").equals(e.getPin())
                                   .collect(Collectors.toList());