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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With