Collectors CollectingAndThen Unmodifiable
Wrap a downstream collector with collectingAndThen so grouped results finish as unmodifiable lists instead of mutable ArrayList defaults.
Code
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FrozenGroups {
record Book(String genre, String title) {}
public static void main(String[] args) {
Stream<Book> shelf = Stream.of(
new Book("sf", "Dune"),
new Book("sf", "Hyperion"),
new Book("history", "SPQR"));
// collectingAndThen:下游收完列表后立即包一层不可变视图
Map<String, List<String>> titles = shelf.collect(Collectors.groupingBy(
Book::genre,
Collectors.collectingAndThen(
Collectors.mapping(Book::title, Collectors.toList()),
Collections::unmodifiableList)));
// 直接往分组里塞值会立刻抛 UnsupportedOperationException
try {
titles.get("sf").add("hack");
} catch (UnsupportedOperationException e) {
System.out.println("immutable: " + e.getClass().getSimpleName());
}
System.out.println(titles);
}
}How it works
Collectors CollectingAndThen Unmodifiable is built around the classes FrozenGroups and Book and the function main.
The transformation is expressed as a stream chain and executed once by the collector.
Putting it to use
Running the file prints labeled results such as immutable: — each operation’s effect is visible in the output.
Core lines
Map<String, List<String>> titles = shelf.collect(Collectors.groupingBy(
Book::genre,
Collectors.collectingAndThen(
Collectors.mapping(Book::title, Collectors.toList()),
Collections::unmodifiableList)));
Interactive Tools for This Topic
FAQ
- What does Collectors CollectingAndThen Unmodifiable print when run?
- No setup needed: run the file and look for labeled lines like `immutable:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.