Ответ
Элементы Stream можно собрать в стандартные и кастомные коллекции с помощью статических методов класса Collectors.
Основные коллекторы:
-
В стандартные неизменяемые коллекции:
List<String> list = stream.collect(Collectors.toList()); Set<String> set = stream.collect(Collectors.toSet()); -
В конкретную реализацию: Используйте
Collectors.toCollection(Supplier), чтобы указать конкретный тип.// В LinkedList LinkedList<String> linkedList = stream.collect( Collectors.toCollection(LinkedList::new) ); // В TreeSet TreeSet<String> treeSet = stream.collect( Collectors.toCollection(TreeSet::new) ); -
В Map: Используйте
Collectors.toMap()илиCollectors.groupingBy().// toMap: ключ, значение Map<String, Integer> map = stream.collect( Collectors.toMap(s -> s, String::length) ); // groupingBy: группировка по критерию Map<Integer, List<String>> mapByLength = stream.collect( Collectors.groupingBy(String::length) ); -
В неизменяемые (unmodifiable) коллекции (Java 10+):
List<String> unmodifiableList = stream.collect(Collectors.toUnmodifiableList()); Set<String> unmodifiableSet = stream.collect(Collectors.toUnmodifiableSet()); Map<String, Integer> unmodifiableMap = stream.collect( Collectors.toUnmodifiableMap(s -> s, String::length) );
Почему toCollection? Методы toList() и toSet() не гарантируют тип возвращаемой реализации (это может быть ArrayList или HashSet). toCollection() дает полный контроль.