Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 213
Nalini Wanjale Avatar asked Dec 12 '19 10:12

Nalini Wanjale


2 Answers

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
like image 107
Naman Avatar answered Sep 30 '22 01:09

Naman


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.

like image 45
Eran Avatar answered Sep 30 '22 03:09

Eran