Which List <E> returns Collectors.toList ()?

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

The Streams section has the following:

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

The document does not indicate that there are actually shapes , and I do not know if this even matters.

What bothers me is: Which specific List returns this block of code?

  • It sets the variable to List<Shape> , which is quite normal.
  • stream() and filter() decide which list to use.
  • Collectors.toList() does not specify a specific type of List .

So what kind of concrete (subclass) List used here? Are there any warranties?

+43
java list lambda java-8 collectors
Feb 20 '14 at 15:32
source share
3 answers

So, what specific type (subclass) of List is used here? Are there any warranties?

If you look at the Collectors#toList() documentation, it says that - "There are no guarantees regarding the type, variability, serializability, or stream safety of the list is returned." If you want a specific 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 lambda you can return any implementation that you need List<Shape> .

Update

Or you can even use the method reference:

 List<Shape> blue = shapes.stream() .filter(s -> s.getColor() == BLUE) .collect(Collectors.toCollection(LinkedList::new)); 
+64
Feb 20 '14 at 15:42
source share

Navigating Netbeans (Ctrl + Click), I landed in this code. It seems to be using ArrayList as a provider.

 public static <T> Collector<T, ?, List<T>> toList() { return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, CH_ID); } 
+6
Feb 20 '14 at 16:03
source share

It does not matter, but the specific type is not general, since indeed all types are not universal at run time.

So, what specific type (subclass) of List is used here? Are there any warranties?

I don't think so, but an ArrayList or LinkedList seems likely.

0
Feb 20 '14 at 15:38
source share



All Articles