简体   繁体   English

如何查找列表是否包含多个谓词Java Lambda

[英]How to find if list contains multiple predicates Java Lambda

I am trying to figure out how to do multiple predicate on a single filter in Java Lambda but not had much luck. 我试图弄清楚如何在Java Lambda中的单个过滤器上执行多个谓词,但没有太多运气。

I have a list of Strings 我有一个字符串列表

List<String> namesList = new ArrayList(){};
namesList.add("John");
namesList.add("Jane");
namesList.add("Smith");
namesList.add("Roger");

I have two if statements below in pseudologic that i want to test but not sure how to do it with lambda (i can do it old school method but trying to learn here). 我在pseudologic中有两个if语句,我想测试但不知道如何用lambda做(我可以做旧学校的方法,但试着在这里学习)。

if nameslist contains John and Roger
   print "John & Roger"

if nameslist contains Jane and Smith
   print "Jane Smith"

Using Java lambda how can i test for both scenarios on the list? 使用Java lambda如何测试列表中的两个场景?

Don't use streams: Just convert English to code: 不要使用流:只需将英语转换为代码:

if (namesList.contains("John") && namesList.contains("Roger"))
    System.out.println("John & Roger");

Or 要么

if (namesList.containsAll(Arrays.asList("John", "Roger")))
    System.out.println("John & Roger");

It's easier to read and will likely perform as well or better than the stream-based approach. 它更容易阅读,并且可能比基于流的方法表现更好或更好。

A lambda is not the right approach. lambda不是正确的方法。

I would do it as follows: 我会这样做:

    if (namesList.stream()
            .filter(x -> (x.equals("John") || x.equals(("Roger"))))
            .collect(Collectors.toSet())
            .size() == 2) {
        System.out.print("John & Roger");
    }

    if (namesList.stream()
            .filter(x -> (x.equals("Jane") || x.equals(("Smith"))))
            .collect(Collectors.toSet())
            .size() == 2) {
        System.out.print("Hane Smith");
    }

You could combine distinct and count: 你可以结合不同和计数:

if (namesList.stream()
        .filter(s -> s.equals("John") || s.equals("Roger"))
        .distinct()
        .count() == 2) {
    System.out.print("John & Roger");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM