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!
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.
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.
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:
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 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.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.
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.
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! 🎉