Predicate And Or Negate Filters
Build compound filters from small predicates with and, or, and negate, so each rule stays a one-line test that reads like the requirement.
Code
import java.util.List;
import java.util.function.Predicate;
public class OrderFilter {
record Order(String status, int cents, boolean gift) {}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("paid", 1200, false),
new Order("pending", 500, false),
new Order("paid", 80, true),
new Order("shipped", 6400, false));
Predicate<Order> isPaid = o -> "paid".equals(o.status());
Predicate<Order> isExpensive = o -> o.cents() >= 1000;
// and:两个条件同时成立
Predicate<Order> paidAndBig = isPaid.and(isExpensive);
// or:任一条件成立即可
Predicate<Order> bigOrGift = isExpensive.or(Order::gift);
// negate:原地取反,不必手写 ! 链
Predicate<Order> notPaid = isPaid.negate();
orders.stream()
.filter(paidAndBig)
.forEach(o -> System.out.println("paid + expensive: " + o));
System.out.println("not big and not gift = "
+ orders.stream().filter(bigOrGift.negate()).count());
System.out.println("pending or shipped = "
+ orders.stream().filter(notPaid).count());
}
}Inside the snippet
Count the classes OrderFilter and Order and the function main as the entire surface area of Predicate And Or Negate Filters.
The transformation is expressed as a stream chain and executed once by the collector.
Using it
Running the file prints labeled results such as paid + expensive:, not big and not gift =, pending or shipped = — each operation’s effect is visible in the output.
Key statements
.filter(paidAndBig)
.forEach(o -> System.out.println("paid + expensive: " + o));
FAQ
- What does Predicate And Or Negate Filters print when run?
- Run it as a complete program — the output lines carry labels such as `paid + expensive:`, `not big and not gift =`, `pending or shipped =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.