Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 streams to find multiple values and return boolean

I am using java-8 to find the values in list of custom object. For ex)

List<Employee> employees = Arrays.asList(
        new Employee("Sachin Tendulkar", 41),
        new Employee("Sachin Tendulkar", 36),
        new Employee("MS Dhoni", 34),
        new Employee("Rahul Dravid", 40),
        new Employee("Lokesh Rahul", 25),
        new Employee("Sourav Ganguly", 40)
);

To find a value in a list i can use the below query,

boolean isPresent = employees.stream()
            .allMatch(employee -> (equalsIgnoreCase(employee.getName(),"Sachin Tendulkar") && equalsIgnoreCase(employee.getAge(),"36")));

The above is working fine. But I would like to find "Sachin Tendulkar" with Age 36 and "Rahul Dravid" with 40. How to achieve this in Java8 streams. I have tried multiple "allMatch" but that doesn't work.

Any hint would be appreciable.

like image 576
VelNaga Avatar asked Jun 26 '18 21:06

VelNaga


2 Answers

You can use anyMatch like so :

boolean isPresent = employees.stream()
        .anyMatch(employee ->
                (employee.getName().equalsIgnoreCase("Sachin Tendulkar") && employee.getAge() == 36)
                        ||
                        (employee.getName().equalsIgnoreCase("Rahul Dravid") && employee.getAge() == 40)
        );

To get the Employee list you can use :

List<Employee> result = employees.stream()
        .filter(employee ->
                (employee.getName().equalsIgnoreCase("Sachin Tendulkar") && employee.getAge() == 36)
                        ||
                        (employee.getName().equalsIgnoreCase("Rahul Dravid") && employee.getAge() == 40)
        ).collect(Collectors.toList());

Or you can create a List of Employee that you want to find and just use List::containsAll, note you have to override hashCode and equals method in your Employee class :

List<Employee> listToFind = Arrays.asList(
        new Employee("Sachin Tendulkar", 36),
        new Employee("Rahul Dravid", 40)
);

boolean isPresent = employees.containsAll(listToFind);
like image 115
YCF_L Avatar answered Sep 23 '22 07:09

YCF_L


Here's a more readable solution,

Predicate<Employee> p1 = e -> e.getName().equals("Sachin Tendulkar") && e.getAge() == 36;
Predicate<Employee> p2 = e -> e.getName().equals("Rahul Dravid") && e.getAge() == 40;
final boolean isFound = employees.stream().filter(p1.or(p2)).findAny().isPresent();

A more condensed solution would be,

final boolean isFound = employees.stream().anyMatch(p1.or(p2));
like image 37
Ravindra Ranwala Avatar answered Sep 21 '22 07:09

Ravindra Ranwala