When to Use Primitive Specializations vs Generics
You'll learn: How to decide whether to use primitive-specific functional interfaces or their generic equivalents for better performance and cleaner code.
The Core Decision Criteria
Now that you've seen all the primitive specializations (like IntPredicate, DoubleConsumer, LongBinaryOperator), you need to know when to choose them over generic versions like Predicate<Integer>, Consumer<Double>, or BinaryOperator<Long>.
Think of it like choosing between a direct flight and one with layovers: primitive specializations are the direct route—faster and more efficient—while generics with boxed types add unnecessary stops (boxing/unboxing overhead).
Decision Rules
Use primitive specializations when:
- Working with primitive streams (
IntStream,LongStream,DoubleStream) — the API is designed for these types - Performance matters — avoid boxing/unboxing overhead in hot code paths
- Processing large volumes — the cumulative cost of boxing millions of primitives is significant
- The primitive type is already known — why box an
intwhen you can useIntPredicatedirectly?
Use generics when:
- Working with object streams (
Stream<T>) — you're already dealing with objects - Need flexibility — the same logic applies to multiple types
- Type is unknown at design time — truly generic algorithms
- Boxing is unavoidable anyway — data already comes from a
List<Integer>
Quick Example of the Trade-off
If you're filtering a range of integers: IntPredicate avoids boxing. But if you're filtering a List<Integer> that's already boxed: Predicate<Integer> is fine since boxing already occurred.
Key Takeaway: Choose primitive specializations when working directly with primitives for performance; use generics when dealing with objects or when type flexibility is essential. Let the data source guide your choice.