如何解决过滤对象中的子列表并返回Java 8
我需要一个雇员对象,该对象的地址应从该对象下面开始,其引脚为40001。
Employee eObj= new Employee(1,"abc",10001,Arrays.asList(new Address("ad1","ad2","tel","40001"),new Address("ad1","tel1","40002")));
//需要帮助以编写下面的逻辑
Employee filteredEobj ={Logic}
//期望的响应
new Employee(1,"40001"));
How can we achieve this using java 8?
解决方法
流
假设您具有相应的吸气剂,并要求提供流变体:
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(),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(),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(),addresses);
,
您可以先过滤地址,然后使用新地址的数据创建员工。
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
的使用者正在学习,因为您尚未显示课程。
List<Employee> employees = empObjs.stream()
.filter(e -> ("40001").equals(e.getPin())
.collect(Collectors.toList());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。