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.
List<String> list = stream.collect(Collectors.toList());

Enter fullscreen mode Exit fullscreen mode

  1. toSet(): Collects all Stream elements into a Set instance.
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.
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.
String joined = stream.collect(Collectors.joining(", "));

Enter fullscreen mode Exit fullscreen mode

  1. counting(): Counts the number of elements in the Stream.
Long count = stream.collect(Collectors.counting());

Enter fullscreen mode Exit fullscreen mode

  1. summingInt(), summingLong(), summingDouble(): Sums the Stream elements.
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.
Optional<String> max = stream.collect(Collectors.maxBy(Comparator.naturalOrder()));

Enter fullscreen mode Exit fullscreen mode

  1. collectingAndThen(): Performs an additional finishing transformation.
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.

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.

原文链接:Exploring Java Collectors utilities

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容