DEV Community

Basu
Basu

Posted on

5

Exploring Java Collectors utilities

In Java, the java.util.stream.Collectors class provides a number of useful methods for performing reductions on streams. Here are some commonly used ones:

  1. toList(): Collects all Stream elements into a List instance. Image description
List<String> list = stream.collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode
  1. toSet(): Collects all Stream elements into a Set instance. Image description
Set<String> set = stream.collect(Collectors.toSet());
Enter fullscreen mode Exit fullscreen mode
  1. toMap(): Creates a Map instance from the Stream elements, with the first function serving as the map's keys and the second function as the values. Image description
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
Enter fullscreen mode Exit fullscreen mode
  1. joining(): Concatenates all Stream elements into a String. Image description
String joined = stream.collect(Collectors.joining(", "));
Enter fullscreen mode Exit fullscreen mode
  1. counting(): Counts the number of elements in the Stream. Image description
Long count = stream.collect(Collectors.counting());
Enter fullscreen mode Exit fullscreen mode
  1. summingInt(), summingLong(), summingDouble(): Sums the Stream elements. Image description
Integer sum = stream.collect(Collectors.summingInt(Integer::intValue));
Enter fullscreen mode Exit fullscreen mode
  1. maxBy(), minBy(): Finds the maximum or minimum Stream element according to a provided Comparator. Image description
Optional<String> max = stream.collect(Collectors.maxBy(Comparator.naturalOrder()));
Enter fullscreen mode Exit fullscreen mode
  1. collectingAndThen(): Performs an additional finishing transformation. Image description
List<String> unmodifiableList = stream.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
Enter fullscreen mode Exit fullscreen mode
  1. partitioningBy(): Partitions the Stream elements into a Map according to a Predicate.

Image description

Map<Boolean, List<String>> partitioned = stream.collect(Collectors.partitioningBy(s -> s.length() > 5));
Enter fullscreen mode Exit fullscreen mode

These are just a few examples. The Collectors class provides many more utility methods for common tasks.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs