Which is the best way to create a stream out of a collection:
final Collection<String> entities = someService.getArrayList();
entities.stream();
Stream.of(entities);
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
of() have different return types. For example, if we pass a primitive integer array, the Stream. of() method returns Stream<int[]> , whereas Arrays. stream() returns an IntStream .
Generating Streams With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
What is the difference between both? IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.
The second one does not do what you think it does! It does not give you a stream with the elements of the collection; instead, it will give you a stream with a single element, which is the collection itself (not its elements).
If you need to have a stream containing the elements of the collection, then you must use entities.stream()
.
1)
Stream<String> stream1 = entities.stream()
2)
Stream<Collection<String>> stream2 = Stream.of(entities)
So use 1, or for 2
Stream<String> stream3 = Stream.of("String1", "String2")
We can take a look at the source code:
/**
* Returns a sequential {@code Stream} containing a single element.
*
* @param t the single element
* @param <T> the type of stream elements
* @return a singleton sequential stream
*/
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
/**
* Returns a sequential ordered stream whose elements are the specified values.
*
* @param <T> the type of stream elements
* @param values the elements of the new stream
* @return the new stream
*/
@SafeVarargs
@SuppressWarnings("varargs") // Creating a stream from an array is safe
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
As for Stream.of()
, when the input variable is an array, it will call the second function, and return a stream containing the elements of the array. When the input variable is a list, it will call the first function, and your input collection will be treated as a single element, not a collection.
So the right usage is :
List<Integer> list = Arrays.asList(3,4,5,7,8,9);
List<Integer> listRight = list.stream().map(i -> i*i).collect(Collectors.toList());
Integer[] integer = list.toArray(new Integer[0]);
List<Integer> listRightToo = Stream.of(integer).map(i ->i*i).collect(Collectors.toList());
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