In this post we will see Collectors examples which used to collect elements.

Collectors Examples

  • The collect method is used to perform a reduction operation on a stream
  • Used to collect the elements into a collection as a list, set, or map.
  • collect method takes as an argument a Collector object, which defines the reduction operation to be performed and the target collection to collect the elements into.

Convert String array into comma separated string:

String joined = Stream.of("apple", "banana", "orange")
                .collect(Collectors.joining(", "));

In the above example, the Collectors.joining(", ") method returns a collector that joins the elements of the stream into a single string, separated by a comma and a space.

Averaging the elements of a stream of numbers:

Double average = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.averagingInt(n -> n));

In this example, the Collectors.averagingInt(n -> n) method returns a collector that computes the average of the elements of the stream by applying the provided function to each element and averaging the results.

Summing the elements of a stream of numbers:

Integer sum = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.summingInt(n -> n));

In this example, the Collectors.summingInt(n -> n) method returns a collector that computes the sum of the elements of the stream by applying the provided function to each element and summing the results.

Counting the number of elements in a stream:

Long count = Stream.of("apple", "banana", "orange")
                .collect(Collectors.counting());

In this example, the Collectors.counting() method returns a collector that counts the number of elements in the stream.

Finding the maximum and minimum elements in a stream of numbers:

OptionalInt max = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.maxBy(Integer::compareTo));
OptionalInt min = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.minBy(Integer::compareTo));

In this example, the Collectors.maxBy(Integer::compareTo) method returns a collector that finds the maximum element in the stream by comparing the elements using the provided comparator function and the Collectors.minBy(Integer::compareTo) finds the minimum element in the stream by comparing the elements using the provided comparator function

Grouping elements of a stream by a certain criteria:

Map<Integer, List<String>> grouped = Stream.of("apple", "banana", "orange")
                .collect(Collectors.groupingBy(String::length));

In this example, the Collectors.groupingBy(String::length) method returns a collector that groups the elements of the stream by their length. The resulting map has the length of the strings as the key and a list of strings with that length as the value.

Partitioning elements of a stream by a certain criteria:

Map<Boolean, List<Integer>> partitioned = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.partitioningBy(n -> n % 2 == 0));

In this example, the Collectors.partitioningBy(n -> n % 2 == 0) method returns a collector that partitions the elements of the stream into two groups: those that satisfy the provided predicate (even numbers) and those that don’t (odd numbers). The resulting map has a Boolean value as the key (true for even numbers, false for odd numbers) and a list of integers as the value.

Summarizing elements of a stream of numbers:

IntSummaryStatistics summary = Stream.of(1, 2, 3, 4, 5)
                .collect(Collectors.summarizingInt(n -> n));

In this example, the Collectors.summarizingInt(n -> n) method returns a collector that computes various statistics about the elements of the stream, such as the count, sum, minimum, maximum, and average. The resulting object is an instance of IntSummaryStatistics.

Collecting elements of a stream into a custom collection:

Set<String> set = Stream.of("apple", "banana", "orange")
                .collect(Collectors.toCollection(LinkedHashSet::new));

In this example, the Collectors.toCollection(LinkedHashSet::new) method returns a collector that collects the elements of the stream into an instance of the provided collection factory.

Collecting elements of a stream into a Map:

Map<Integer,String> map = Stream.of("apple", "banana", "orange")
                .collect(Collectors.toMap(s->s.length(),s->s));

In this example, the Collectors.toMap(s->s.length(),s->s) method returns a collector that collects the elements of the stream into a Map, where the first argument is the key and the second argument is the value.

collect the elements of a stream into a list:

List<Integer> numbers = Stream.of(1, 2, 3, 4, 5)
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList());

In this example, the Stream.of(1, 2, 3, 4, 5) method creates a stream of integers, the filter method filters the stream to only even numbers, and the collect(Collectors.toList()) method collects the remaining elements into a list.

using the collect method to collect elements into a set:

Set<String> words = Stream.of("apple", "banana", "apple", "orange")
                .collect(Collectors.toSet());

In this example, the Stream.of("apple", "banana", "apple", "orange") creates a stream of strings, and the collect(Collectors.toSet()) method collects the elements into a set, discarding any duplicate elements.

Collectors. groupingBy Example

Here is an example of using the groupingBy collector to group the elements of a stream by their length:

Map<Integer, List<String>> wordsByLength = words.stream()
                .collect(Collectors.groupingBy(String::length));

In this example, the Collectors.groupingBy(String::length) method returns a collector that groups the elements of the stream by their length, and the collect method collects the elements into a map where the keys are the lengths and the values are lists of words with that length.

Thanks for Reading..