简体   繁体   中英

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.

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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