好的,我想使用Predicate.or(其他)而不是写||在Predicate中,但是当我使用removeList的ArrayList时,看起来这里只执行了第一次检查是一个代码示例:
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 []
}
答案 0 :(得分:3)
or
会返回一个新的Predicate
,但您忽略了返回的值:
Predicate<String> predicate = str -> str.equals("A");
predicate = predicate.or(str -> str.equals("B"));
predicate = predicate.or(str -> str.equals("C"));
答案 1 :(得分:2)
predicate.or(str -> str.equals("B"))
不会改变原始Predicate
,它会返回一个新的。{/ p>
您需要将返回的Predicate
分配给predicate
变量:
Predicate<String> predicate = str -> str.equals("A");
predicate = predicate.or(str -> str.equals("B"));
predicate = predicate.or(str -> str.equals("C"));
答案 2 :(得分:1)
你忽略了or
方法的结果,结果是:
相反,请执行:
predicate = predicate.or(str -> str.equals("B"))
.or(str -> str.equals("C"));