Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am reading State of the Lambda: Libraries Edition, and am being surprised by one statement:

Under the section Streams, there is the following:

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

The document does not state what shapes actually is, and I do not know if it even matters.

What confuses me is the following: What kind of concrete List does this block of code return?

  • It assigns the variable to a List<Shape>, which is completely fine.
  • stream() nor filter() decide what kind of list to use.
  • Collectors.toList() neither specifies the concrete type of List.

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

like image 878
skiwi Avatar asked Feb 20 '14 15:02

skiwi


People also ask

What does collectors toList () do?

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

Does collectors toList return empty List?

Collector. toList() will return an empty List for you. As you can see ArrayList::new is being used as a container for your items.

What implementation of List does the collectors toList () create?

toList(), collects the elements into an unmodifiable List. Though the current implementation of the Collectors. toList() creates a mutable List, the method's specification itself makes no guarantee on the type, mutability, serializability, or thread-safety of the List. On the other hand, both Collectors.

Is toList immutable?

toList() returns an immutable list. So, trying to add a new element to the list will simply lead to UnsupportedOperationException.


1 Answers

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)); 
like image 171
Rohit Jain Avatar answered Oct 05 '22 00:10

Rohit Jain