221.
In addition to sequential streams,
the Stream API also supports
parallel streams. Parallel streams operate concurrently on the
elements in a Stream and
hence provide a performance
improvement. A new method called parallelStream() has
been added to the Collection interface. This can be used to
obtain a parallel stream corresponding
to the underlying
collection. The following code demonstrates this:
List
colours =
Arrays.asList(“Red”,”Green”,”Blue”);
Stream parallelStream =
colours.parallelStream();
This code first creates a List of String values called colours. It
then invokes the parallelStream() method on the colours
List. This returns a parallel stream corresponding to the List. Any
further Stream operations performed on this stream will be
executed concurrently on the elements in the Stream.
How can you convert a Stream back to a Collection?
Answer:
The Stream interface has a method called collect(). This can
be used to convert a Stream back to a Collection. The following
code demonstrates this:
Stream numbers = Stream.of(7,3,9,6,1);
List filteredList = numbers.filter(num–> num >
5).collect(Collectors.toList());
This code first creates a List of Integers. It then invokes the
filter() method to obtain the numbers that are greater than 5.
After that, it invokes the collect() method. The collect()
222.
223.
method accepts as parameter a Collector. The
Collectors.toList() method
is invoked which returns a
Collector that converts the input Stream to a List. So, the
filteredList is a List that has only the numbers that are
greater than 5 from the input List. There
are other methods in the
Collectors class like Collectors.toSet,
Collectors.toMap, Collectors.toCollection which can
be used to convert the Stream to other types of Collections.
Do'stlaringiz bilan baham: