Collectors.collectingAndThen
时间: 2024-02-06 20:03:40 浏览: 75
collector
`Collectors.collectingAndThen` is a static method in the `java.util.stream.Collectors` class that allows you to perform a final transformation on the result of a collector. It takes two arguments: a collector and a `Function` that performs the final transformation.
The `collectingAndThen` method returns a collector that applies the specified collector to the elements of a stream, and then applies the specified function to the result of the collector.
Here's an example of how to use `collectingAndThen` to collect a list of strings, convert it to uppercase, and then return the result as an unmodifiable list:
```
List<String> words = Arrays.asList("hello", "world", "java");
List<String> upperCaseWords = words.stream()
.collect(Collectors.collectingAndThen(
Collectors.toList(),
list -> Collections.unmodifiableList(list.stream()
.map(String::toUpperCase)
.collect(Collectors.toList()))));
System.out.println(upperCaseWords);
```
Output:
```
[HELLO, WORLD, JAVA]
```
In this example, the `collectingAndThen` method first applies the `toList` collector to the stream of strings, which collect them into a mutable `List<String>`. Then, it applies a lambda expression that transforms the list into an unmodifiable list of uppercase strings using the `map` and `collect` methods. Finally, it returns the resulting unmodifiable list.
阅读全文