1. Overview
1.概述
In this quick tutorial, we’ll learn how to find items from one list based on values from another list using Java 8 Streams.
在这个快速教程中,我们将学习如何使用Java 8 Streams从一个列表中根据另一个列表的值来查找项目。
2. Using Java 8 Streams
2.使用Java 8 Streams
Let’s start with two entity classes – Employee and Department:
让我们从两个实体类开始 – Employee 和Department。
class Employee {
Integer employeeId;
String employeeName;
// getters and setters
}
class Department {
Integer employeeId;
String department;
// getters and setters
}
The idea here is to filter a list of Employee objects based on a list of Department objects. More specifically, we want to find all Employees from a list that:
这里的想法是根据Department对象的列表来过滤Employee对象的列表。更具体地说,我们想从一个列表中找到所有的Employees,这些对象。
- have “sales” as their department and
- have a corresponding employeeId in a list of Departments
And to achieve this, we’ll actually filter one inside the other:
为了实现这一点,我们实际上将在另一个里面进行过滤。
@Test
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
Integer expectedId = 1002;
populate(emplList, deptList);
List<Employee> filteredList = emplList.stream()
.filter(empl -> deptList.stream()
.anyMatch(dept ->
dept.getDepartment().equals("sales") &&
empl.getEmployeeId().equals(dept.getEmployeeId())))
.collect(Collectors.toList());
assertEquals(1, filteredList.size());
assertEquals(expectedId, filteredList.get(0)
.getEmployeeId());
}
After populating both the lists, we simply pass a Stream of Employee objects to the Stream of Department objects.
在填充这两个列表后,我们只需将一个雇员对象的流传递给部门对象的流。
Next, to filter records based on our two conditions, we’re using the anyMatch predicate, inside which we have combined all the given conditions.
接下来,为了根据我们的两个条件过滤记录,我们使用了anyMatch谓词,里面我们结合了所有的给定条件。
Finally, we collect the result into filteredList.
最后,我们收集结果到filteredList。
3. Conclusion
3.结论
In this article, we learned how to:
在这篇文章中,我们学会了如何。
- Stream values of one list into the other list using Collection#stream and
- Combine multiple filter conditions using the anyMatch() predicate
The full source code of this example is available over on GitHub.
这个例子的完整源代码可以在GitHub上找到,。