'Java 8 get all employee having address start with P
I have employee and address class as below
class Employee {
private String name;
private int age;
private List<Address> addresses;
//getter and setter
}
class Address {
private String city;
private String state;
private String country;
//getter and setter
}
Using java 8 filter I want to print all employees who are having city starting with P
What to add to below code to get emp of that filtered address
employees.stream()
.map(Employee::getAddresses)
.flatMap(Collection::stream)
.filter(children -> children.getCity().startsWith("p"))
.collect(Collectors.toList())
.forEach(System.out::println);
Thanks in advance.
Solution 1:[1]
Use anyMatch in filter instead of mapping :
employees.stream()
.filter(employee -> employee.getAddresses().stream()
.anyMatch(adr -> adr.getCity().startsWith("p")))
.forEach(System.out::println); // collecting not required to use forEach
Solution 2:[2]
You shouldn't map the Employee instances into their addresses if you want to print the Employees that have an address that passes your filtering criteria:
employees.stream()
.filter(e -> e.getAddresses()
.stream()
.anyMatch(addr -> addr.getCity().startsWith("p")))
.forEach(System.out::println);
Note that there's no reason to collect the Stream into a List if all you are going to do with the List is iterate over it with forEach.
Solution 3:[3]
It is case sensitive and the question is about 'P',
employees.stream()
.filter(employee -> employee.getAddresses().stream()
.anyMatch(adr -> adr.getCity().startsWith("P")))
.forEach(System.out::println);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sumit Singh |
| Solution 3 | Arafath |
