1. Overview
In this quick tutorial, we’ll learn how to find items from one list based on values from another list using Java 8 Streams.
2. Using Java 8 Streams
Let’s start with two entity classes – Employee and 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:
- 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.
Finally, we collect the result into filteredList.
3. Conclusion
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.