Core java interview Questions You'll Most Likely Be Asked (Second Edition)


What is a parallel stream? Explain with a code sample


Download 1.52 Mb.
Pdf ko'rish
bet83/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   79   80   81   82   83   84   85   86   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

What is a parallel stream? Explain with a code sample
how you can create a parallel stream.
Answer:


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.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   79   80   81   82   83   84   85   86   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling