Java Streams - Collectors toList() example








Collectors toList() returns a Collector that accumulates the input elements into a new List.

Syntax

toList has the following syntax.

public static <T> Collector<T,?,List<T>> toList()

Example

The following example shows how to use toList.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//from w  ww.ja v a  2s.  c o m
public class Main {
  public static void main(String[] args) {
    Stream<String> s = Stream.of("a","b","c");
    
    List<String> names = s
        .collect(Collectors.toList());

    System.out.println(names);
  }
}

The code above generates the following result.