英文:
Filter a list based on some values and again filter the result on first output
问题
以下是翻译好的部分:
我目前有一个情况,我有一个列表,我根据其中的值进行过滤,然后根据结果再次进行过滤。
for (Employee emp : data.getEmployees()) {
if (emp.getAge() > 30) {
for (Position position : emp.getPositions()) {
if (position.getName().equalsIgnoreCase("Manager")) {
return position;
}
}
}
}
如何在使用 Java 8 的流(Stream)呢?
data.getEmployees().stream().filter(emp -> emp.getAge() > 30)
不确定如何进一步使用。因为这只会得到员工列表,我只想要职位是经理的员工列表。
英文:
I currently have a scenario where I have a List and I filter based on the values inside this and I need to filter again based on the outcome.
for (Employee emp : data.getEmployees()) {
if (emp.getAge() > 30) {
for (Position position : emp.getPositions()) {
if (position.getName().equalsIgnoreCase("Manager")) {
return position;
}
}
}
}
How to use it using Java 8 stream?
data.getEmployees().stream().filter(emp -> emp.getAge>30)
Not sure on how to use it further. As this will just result in the list of employees I just want the list of employee with position as manager
答案1
得分: 3
我假设您要获取“Position”或这些的流:
data.getEmployees().stream()
.filter(emp -> emp.getAge > 30)
.flatMap(emp -> emp.getPositions().stream())
.filter(pos -> "Manager".equalsIgnoreCase(pos.getName()))
flatMap
创建一个包含由参数中的所有元素的流的所有元素的新流。
或者要获取所有的经理员工:
data.getEmployees().stream()
.filter(emp -> emp.getAge > 30)
.filter(emp -> emp.getPositions().stream().anyMatch(pos ->
"Manager".equalsIgnoreCase(pos.getName())
))
它只是创建了所有员工的职位的新流,并测试是否有一个职位名称为 Manager
。
如果您想将其作为列表获取,只需添加 .collect(Collectors.toList())
。
英文:
I assume you want to either get the Position
s or a stream of those:
data.getEmployees().stream()
.filter(emp -> emp.getAge>30)
.flatMap(emp->emp.getPositions().stream())
.filter(pos->"Manager". equalsIgnoreCase (pos.getName()))
flatMap
creates a new stream containing all elements of the streams found by the parameter of all elements.
Or to get all employees that are managers:
data.getEmployees().stream()
.filter(emp -> emp.getAge>30)
.filter(emp->emp.getPositions().stream().anyMatch(pos->
"Manager". equalsIgnoreCase (pos.getName())
))
It just creates a new stream of the positions of all employees and tests if there is one with the name Manager
.
If you want to e.g. get it as list, you can just append .collect(Collectors.toList())
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论