Java Stream How to - Collect/Convert Stream to List








Question

We would like to know how to collect/Convert Stream to List.

Answer

/*from   w  w  w .  j ava 2  s . c o  m*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    // collect as typed array
    Stream<String> words = Stream.of("All", "men", "are", "created", "equal");
    List<String> wordsList = words.collect(ArrayList::new, ArrayList::add,
        ArrayList::addAll);
    wordsList.forEach(n -> System.out.println(n));
  }
}

The code above generates the following result.