简体   繁体   中英

Java 8 predicate OR and removeIf strange behavior

Ok so have I wanted to use Predicate.or(other) instead of writing || inside a Predicate but when I am using with removeIf of ArrayList it looks like only the first check is performed here is a code example:

    public static void main(String... args) {
    List<String> leters = new ArrayList<>(Arrays.asList("A", "B", "C"));
    Predicate<String> predicate = str -> str.equals("A");
    predicate.or(str -> str.equals("B"));
    predicate.or(str -> str.equals("C"));
    leters.removeIf(predicate);
    System.out.println(leters); // Prints B,C. I was acpecting to get an empty list

    Predicate<String> predicate2 = str -> str.equals("A") || str.equals("B") || str.equals("C");
    leters = new ArrayList<>(Arrays.asList("A", "B", "C"));
    leters.removeIf(predicate2);
    System.out.println(leters); // Prints []
}

or returns a new Predicate but you are ignoring the returned value:

Predicate<String> predicate = str -> str.equals("A");
predicate = predicate.or(str -> str.equals("B"));
predicate = predicate.or(str -> str.equals("C"));

predicate.or(str -> str.equals("B")) doesn't mutate the original Predicate , it returns a new one.

You need to assign the returned Predicate s to the predicate variable:

Predicate<String> predicate = str -> str.equals("A");
predicate = predicate.or(str -> str.equals("B"));
predicate = predicate.or(str -> str.equals("C"));

You're ignoring the result form the or method hence the outcome:

Instead, do:

 predicate = predicate.or(str -> str.equals("B"))
                      .or(str -> str.equals("C"));

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