Java8流查找多个值并返回布尔值

时间:2018-06-26 21:36:50

标签: java java-8 java-stream

我正在使用java-8在自定义对象列表中查找值。对于前)

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

要在列表中查找值,我可以使用以下查询,

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

以上工作正常。但是我想找到36岁的“ Sachin Tendulkar”和40岁的“ Rahul Dravid”。如何在Java8流中实现这一点。我已经尝试了多个“ allMatch”,但这是行不通的。

任何提示都是有意义的。

2 个答案:

答案 0 :(得分:5)

您可以像这样使用anyMatch

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

要获取员工列表,可以使用:

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

或者您可以创建要查找的Employee列表,并仅使用List::containsAll,请注意,您必须在Employee类中覆盖hashCodeequals方法:

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

boolean isPresent = employees.containsAll(listToFind);

答案 1 :(得分:2)

这是一个更具可读性的解决方案,

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

一种更简洁的解决方案,

final boolean isFound = employees.stream().anyMatch(p1.or(p2));