Collect Stream Result Examples

Instead of reducing a stream to a value, we can also collect the results. We can collect results to an array, a set/list, or a map by using the Stream.collect() method.

1. Collect Stream Results to Array

List<String> list = new ArrayList<String>();
list.add("java");
list.add("php");
list.add("python");
Stream<String> wordStream = list.stream();
 
Stream<Integer> lengthStream = wordStream.map(s -> s.length());
Integer[] lenArr = lengthStream.toArray(Integer[]::new);
System.out.println(Arrays.toString(lenArr));

* Note that toArray() is a terminal operation. After toArray() is invoked, the stream is not available to use anymore.

2. Collect Stream Results to List/Set

Collect results to list by using Collectors.toList().

List<Integer> intList= lengthStream.collect(Collectors.toList());

Collect results to list by using Collectors.toSet().

Set<Integer> intSet= lengthStream.collect(Collectors.toSet());

We can also specify the type of set to use like this:

TreeSet<Integer> intSet= lengthStream.collect(Collectors.toCollection(TreeSet::new));

3. Collect Stream Results to Map

List<String> list = new ArrayList<String>();
list.add("java");
list.add("php");
list.add("python");
Stream<String> wordStream = list.stream();
 
// to map
Map<String, Integer> map = wordStream.collect(Collectors.toMap(Function.identity(), s->s.length()));
System.out.println(map);

Output:

{python=6, java=4, php=3}

Leave a Comment