What kind of List does Collectors.toList() return?

So, what concrete type (subclass) of List is being used here? Are there any guarantees?

If you look at the documentation of Collectors#toList(), it states that – “There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned”. If you want a particular implementation to be returned, you can use Collectors#toCollection(Supplier) instead.

Supplier<List<Shape>> supplier = () -> new LinkedList<Shape>();

List<Shape> blue = shapes.stream()
            .filter(s -> s.getColor() == BLUE)
            .collect(Collectors.toCollection(supplier));

And from the lambda, you can return whatever implementation you want of List<Shape>.

Update:

Or, you can even use method reference:

List<Shape> blue = shapes.stream()
            .filter(s -> s.getColor() == BLUE)
            .collect(Collectors.toCollection(LinkedList::new));

Leave a Comment