Primitive Specializations: comparingInt, comparingLong, comparingDouble
What you'll learn: How to use specialized Comparator factory methods that avoid boxing overhead when comparing primitive numeric values.
Why Specialized Methods Matter
When you use Comparator.comparing() with a primitive value, Java must box that primitive into its wrapper type (int → Integer, long → Long, double → Double). This boxing creates temporary objects, which adds memory and performance overhead—especially when sorting large collections.
The specialized methods comparingInt(), comparingLong(), and comparingDouble() work directly with primitive values, bypassing boxing entirely.
The Three Specializations
Each method takes a function that extracts a primitive value from your object:
// Instead of this (causes boxing):
Comparator<Person> byAge = Comparator.comparing(p -> p.getAge());
// Use this (no boxing):
Comparator<Person> byAge = Comparator.comparingInt(p -> p.getAge());
// For long values:
Comparator<File> bySize = Comparator.comparingLong(f -> f.length());
// For double values:
Comparator<Product> byPrice = Comparator.comparingDouble(p -> p.getPrice());
The Performance Win
Think of it like sorting envelopes by weight. The generic comparing() method writes each weight on a sticky note, puts it in an envelope, then sorts the envelopes. The specialized methods just read the weight directly—faster and no extra materials needed.
These methods use functional interfaces like ToIntFunction<T>, ToLongFunction<T>, and ToDoubleFunction<T> instead of the generic Function<T, R>, allowing Java to avoid object creation.
Key Takeaway: Use comparingInt(), comparingLong(), or comparingDouble() instead of generic comparing() when extracting primitive numeric values to eliminate boxing overhead and improve performance.