IntPredicate, LongPredicate, and DoublePredicate
What You'll Learn
You'll discover how primitive-specialized predicate interfaces eliminate boxing overhead when testing primitive values.
The Problem with Generic Predicate
When you use Predicate<Integer> to test an int, Java must wrap (autobox) each primitive into an Integer object. For high-volume operations, this creates unnecessary objects and garbage collection pressure. Remember from the previous lesson: primitive specializations exist to avoid this performance penalty.
The Primitive Predicate Interfaces
Java provides three specialized predicate interfaces that work directly with primitives:
IntPredicate- testsintvaluesLongPredicate- testslongvaluesDoublePredicate- testsdoublevalues
Each has a test method that accepts the corresponding primitive type and returns boolean—no boxing required.
How They Work
Just like Predicate<T>, these interfaces support composition with and(), or(), and negate(). The key difference is the method signature:
Predicate<Integer>hasboolean test(Integer t)IntPredicatehasboolean test(int value)
That small change makes a big performance difference.
When to Use Them
Use primitive predicates whenever you're filtering or testing primitive streams (IntStream, LongStream, DoubleStream) or working with primitive arrays. If you're already using Predicate<Integer> in performance-critical code, switching to IntPredicate can reduce memory allocation and improve speed.
Practical Context
These specialized interfaces shine in stream operations where you're processing thousands or millions of primitive values—like filtering sensor readings, validating numeric data, or processing financial calculations.
Key Takeaway: IntPredicate, LongPredicate, and DoublePredicate are boxing-free versions of Predicate that improve performance when testing primitive values, especially in high-volume stream operations.