Java Stream collect() Tutorial 🎯

beginner
16 min

Java Stream collect() Tutorial 🎯

Welcome to our in-depth guide on the collect() method in Java Stream API! In this tutorial, we'll cover everything you need to know about this powerful tool, from basics to advanced examples. Let's dive right in!

What is Java Stream API? 📝

Java Stream API is a functional programming interface introduced in Java 8. It provides a high-level abstraction to process collections (like arrays and lists) in a declarative manner, making your code cleaner, more efficient, and easier to understand.

Understanding the collect() method 💡

The collect() method is a crucial part of the Java Stream API. It's used to convert a stream into a specific type (like a list, set, or map), or to perform other tasks like aggregating values, grouping, or reducing the stream.

How to use collect()? 💡

The collect() method is a terminal operation in the Java Stream API, meaning it consumes the stream and produces a result. Here's a simple example of using collect() to convert a stream of integers to a list:

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); List<Integer> squares = numbers.stream() .map(i -> i * i) .collect(Collectors.toList());

In this example, we create a list of integers, create a stream from it, square each number, and collect the result into a new list.

The Collectors Class 📝

The Collectors class provides a set of pre-defined collectors that simplify common operations, such as:

  • toList(): Converts a stream to a list.
  • toSet(): Converts a stream to a set.
  • averagingInt(), averagingLong(), averagingDouble(): Computes the average value of a stream.
  • summingInt(), summingLong(), summingDouble(): Computes the sum of a stream.
  • minBy(), maxBy(): Finds the minimum or maximum value in a stream based on a specified comparator.
  • groupingBy(): Groups the elements of a stream based on a key.
  • reducing(): Reduces a stream to a single value by combining elements using a BinaryOperator.

Advanced Examples 💡

Computing the Average Salary in a Department 💡

java
Map<String, Double> avgSalaries = employees .collect(Collectors.groupingBy(Employee::getDepartment)) .entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey(), entry -> entry.getValue().stream() .mapToDouble(Employee::getSalary) .average() .orElse(0.0) ));

In this example, we group employees by department, calculate the average salary for each department, and store the result in a map.

Finding the Most Expensive Items in a Shop 💡

java
Optional<Item> mostExpensiveItem = items .stream() .collect(Collectors.maxBy(Comparator.comparingDouble(Item::getPrice))) .ifPresent(System.out::println);

In this example, we find the most expensive item in a shop by using the maxBy() collector and the ifPresent() method.

Quick Quiz
Question 1 of 1

Which method is used to convert a stream into a specific type (like a list, set, or map)?

That's all for our comprehensive guide on the collect() method in Java Stream API! We hope this tutorial was helpful. Happy coding! 🎉