Java Collectors: Usage Guide

In Java, Collectors is a utility class within the Stream API that is used for performing collection operations on elements within a stream, such as collecting, grouping, filtering, etc.

Collectors offers a variety of static methods, commonly used methods include:

  1. Collect the elements in the Stream into a List using toList().
  2. toSet(): Collect the elements in the Stream to a Set.
  3. joining(): Concatenate the elements in a Stream into a single string.
  4. groupingBy(): group elements in the Stream by a specified condition.
  5. Counting(): Count the number of elements in the Stream.
  6. calculating the sum:求和
  7. find the maximum value, find the minimum value

Sample code:

List<String> list = Arrays.asList("apple", "banana", "cherry");
List<String> collectedList = list.stream().collect(Collectors.toList());

Map<Integer, List<String>> groupByLength = list.stream().collect(Collectors.groupingBy(String::length));
bannerAds