3 Powerful Java Stream Operations Worth Mastering

Transform Your Collection Processing with These 3 Powerful Stream Operations

Yegor Voronyansky
2 min readNov 7, 2024

--

Image by author

Stream operation in Java are powerful tools that can help you write more concise and readable code. In this article I will explore three essential operation that can help reach more readable code.

Before start using Stream API let’s start with a sample data class.

public record Person(
String name,
int age,
String department,
double salary) {}

List<Person> employees = Arrays.asList(
new Person("John", 30, "Engineering", 75000.0),
new Person("Alice", 25, "Engineering", 65000.0),
new Person("Bob", 35, "HR", 55000.0),
new Person("Carol", 28, "Engineering", 70000.0),
new Person("David", 40, "HR", 85000.0)
);

groupingBy

This collector is incredibly useful when you need to group elements by a specific attribute. In example below, the code grouped employees by their department. This way can be used for creating categorized data structures.

Map<String, List<Person>> byDepartment = employees.stream()
.collect(Collectors.groupingBy(Person::department));

groupingBy and averagingDouble

--

--

Yegor Voronyansky
Yegor Voronyansky

Written by Yegor Voronyansky

I am a Software Engineer, JVM enthusiast, cat - lover, part-time surfer.

No responses yet