Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why didn't Stream have a toList() method?

When using the Java 8 streams, it's quite common to take a list, create a stream from it, do the business and convert it back. Something like:

 Stream.of(-2,1,2,-5)         .filter(n -> n > 0)         .map(n -> n * n)         .collect(Collectors.toList()); 

Why there is no short-cut/convenient method for the '.collect(Collectors.toList())' part? On Stream interface, there is method for converting the results to array called toArray(), why the toList() is missing?

IMHO, converting the result to list is more common than to array. I can live with that, but it is quite annoying to call this ugliness.

Any ideas?

like image 352
Jiri Kremser Avatar asked Feb 28 '15 13:02

Jiri Kremser


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 ArrayList?

For instance, Collectors. toList() method can return an ArrayList or a LinkedList or any other implementation of the List interface. To get the desired Collection, we can use the toCollection() method provided by the Collectors class.

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.

Does collector toList create new List?

toList. Returns a Collector that accumulates the input elements into a new List . There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier) .


1 Answers

Recently I wrote a small library called StreamEx which extends Java streams and provides this exact method among many other features:

StreamEx.of(-2,1,2,-5)     .filter(n -> n > 0)     .map(n -> n * n)     .toList(); 

Also toSet(), toCollection(Supplier), joining(), groupingBy() and other shortcut methods are available there.

like image 181
Tagir Valeev Avatar answered Sep 30 '22 17:09

Tagir Valeev