How to use logical operators with Predicate

1. Introduction

This post would demo how to use logical operators with Predicate.

The logical operators include:

  • And
  • Or
  • Negate

Environments

  • Java 1.8

2. Examples

2.1 Use the and operator with Predicate

private static List<String> originList
        = Arrays.asList("a","bc","def","fgha");

private static void demoAnd() {
    //filter strings that contain 'a' and length >3
    Predicate<String> p1 = s->s.contains("a");
    Predicate<String> p2 = s->s.length()>3;
    List<String> filtered =
            originList.stream().
                    filter(p1.and(p2)).//line 1
                    collect(Collectors.toList());
    filtered.stream().forEach(s-> System.out.println(s));
}
  • line 1
    • Here we use the Predicate’s and method, this method would return a Predicate again

2.2 Use the or operator with Predicate

private static void demoOr() {
    //filter strings that contain 'a' or length == 3
    Predicate<String> p1 = s->s.contains("a");
    Predicate<String> p2 = s->s.length()==3;
    List<String> filtered =
            originList.stream().
                    filter(p1.or(p2)).//line 1
                    collect(Collectors.toList());
    filtered.stream().forEach(s-> System.out.println(s));
}
  • line 1
    • Here we use the Predicate’s or method, this method would return a Predicate again

2.3 Use the negate operator with Predicate

private static void demoNegate() {
    //filter strings that not contain 'a'
    Predicate<String> p1 = s->s.contains("a");
    List<String> filtered =
            originList.stream().
                    filter(p1.negate()).//line 1
                    collect(Collectors.toList());
    filtered.stream().forEach(s-> System.out.println(s));
}
  • line 1
    • Here we use the Predicate’s negate method, this method would return a Predicate again

3. The console output of the examples.

demo and 
fgha

demo or
a
def
fgha

demo negate
bc
def

4. summary

In this post we demo how to use logical (and/or/negate) operators with Predicate function.You can find the whole code examples on github.

You can find detail documents about the java lambda here: