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.
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);
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));
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