Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference LongStream VS Stream in Collectors.toList()

Why when I am getting a list from a LongStream with Collectors.toList() got an error but with Stream there is no error?

Examples :

ERROR :

Something.mapToLong(Long::parseLong).collect(Collectors.toList())

Correct :

Something.map(Long::valueOf).collect(Collectors.toList())
like image 716
Omid Ashouri Avatar asked Aug 08 '15 11:08

Omid Ashouri


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 is the use of collectors toList in Java?

The toList() method of Collectors Class is a static (class) method. It returns a Collector Interface that gathers the input data onto a new list. This method never guarantees type, mutability, serializability, or thread-safety of the returned list but for more control toCollection(Supplier) method can be used.

What is Java LongStream?

public interface LongStream extends BaseStream<Long,LongStream> A sequence of primitive long-valued elements supporting sequential and parallel aggregate operations. This is the long primitive specialization of Stream .


1 Answers

There are four distinct classes in Stream API: Stream, IntStream, LongStream and DoubleStream. The latter three are used to process the primitive values int, long and double for better performance. They are tailored for these primitive types and their methods differ much from the Stream methods. For example, there's a LongStream.sum() method, but there's no Stream.sum() method, because you cannot sum any types of objects. The primitive streams don't work with collectors as collectors are accepting objects (there are no special primitive collectors in JDK).

The Stream class can be used to process any objects including primitive type wrapper classes like Integer, Long and Double. As you want to collect to the List<Long>, then you don't need a stream of long primitives, but stream of Long objects. So you need Stream<Long> and map instead of mapToLong. The mapToLong can be useful, for example, if you need a primitive long[] array:

long[] result = Something.mapToLong(Long::valueOf).toArray();
like image 61
Tagir Valeev Avatar answered Nov 06 '22 15:11

Tagir Valeev