Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collectors.toList()

A collector that puts stream elements into a list.

Available since: Java 8

Syntax

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

Return value

Collector<T, ?, List<T>>A collector into a list.

Examples

A modifiable list and a specific collection type:

void main() {
    List<String> list = Stream.of("b", "a").collect(Collectors.toList());
    list.add("c");
    IO.println(list);
    ArrayDeque<String> deque = Stream.of("x", "y").collect(Collectors.toCollection(ArrayDeque::new));
    IO.println(deque.peekLast());
}

Output:

[b, a, c]
y

Notes

The specification does not promise a specific type or mutability (in practice it is an ArrayList). Since Java 16 stream.toList() is shorter for a plain list. If you need a specific collection class, use Collectors.toCollection(ArrayList::new).

See also

  • Stream.toList() — Gathers stream elements into an unmodifiable list.
  • Collectors.toSet() — A collector that puts stream elements into a set without duplicates.
  • Stream.collect() — Gathers stream elements into a collection, a string or another structure.

In the tutorial

  • Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.

Thanks for reading!

Donate to the site — we work hard for you.