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

Real-World Use Cases: Operators in Stream API

See how UnaryOperator and BinaryOperator power map, replaceAll, reduce, and other stream operations efficiently.

Real-World Use Cases: Operators in Stream API

You'll learn how UnaryOperator and BinaryOperator are the workhorses behind common Stream API operations, making transformations and reductions both type-safe and efficient.

Why Operators Matter in Streams

Now that you understand UnaryOperator and BinaryOperator, it's time to see them in action. These functional interfaces aren't just theoretical—they're the foundation of several critical Stream API methods. Think of them as specialized tools: UnaryOperator transforms an item into another of the same type, while BinaryOperator combines two items into one result of that same type.

UnaryOperator in Action

map() with UnaryOperator: When you transform stream elements without changing their type, you're using a UnaryOperator:

List<String> names = List.of("alice", "bob", "charlie");
List<String> uppercase = names.stream()
    .map(String::toUpperCase) // UnaryOperator<String>
    .toList();

replaceAll() on Lists: This method literally takes a UnaryOperator to modify elements in-place:

List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4));
numbers.replaceAll(n -> n * 2); // UnaryOperator<Integer>
// [2, 4, 6, 8]

BinaryOperator in Action

reduce() for Aggregation: Combining stream elements uses BinaryOperator:

int sum = Stream.of(1, 2, 3, 4, 5)
    .reduce(0, Integer::sum); // BinaryOperator<Integer>

String concatenated = Stream.of("Hello", " ", "World")
    .reduce("", String::concat); // BinaryOperator<String>

Finding min/max: The collector methods leverage BinaryOperator.minBy and maxBy internally when you use comparison-based collectors.

Key Takeaway: UnaryOperator powers same-type transformations like map() and replaceAll(), while BinaryOperator drives reduction operations like reduce(), ensuring type consistency and cleaner, more expressive stream pipelines.