Course contentsShow
← Java
Lesson 1698 of 2,87035. Functional InterfacesFree lesson

When to Use Primitive Specializations vs Generics

Learn decision criteria for choosing primitive specializations over generic functional interfaces.

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:

  1. Working with primitive streams (IntStream, LongStream, DoubleStream) — the API is designed for these types
  2. Performance matters — avoid boxing/unboxing overhead in hot code paths
  3. Processing large volumes — the cumulative cost of boxing millions of primitives is significant
  4. The primitive type is already known — why box an int when you can use IntPredicate directly?

Use generics when:

  1. Working with object streams (Stream<T>) — you're already dealing with objects
  2. Need flexibility — the same logic applies to multiple types
  3. Type is unknown at design time — truly generic algorithms
  4. 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.