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?
The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List.
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.
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.
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) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With