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


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

217.
a.
b.
c.
218.
CHAPTER
03
Streams
Explain the different ways in which you can create a
Stream.
Answer:
There are several ways in which you can create a Stream. These
are as follows:
You can directly create a list from a stream of values as
follows:
Stream values = String.of(“Red, “Blue”);
You can create a Stream from a collection as follows:
List numbers = Arrays.asList(1,2,3,4);
Stream stream = numbers.stream();
You can create a Stream from an array as follows:
int[] numbers = new int[] {1,2,3,4};
IntStream arrayStream= Arrays.stream(numbers);
Explain the Stream filter operation with a code sample.
Answer:
The Stream.filter() operation can be used to filter a Stream
based on some condition. So, it creates a new Stream that
consists of only those elements that match the specified


219.
a.
b.
220.
condition. It accepts as parameter a Predicate instance and
filters the elements in the stream based on the specified
predicate. The following code demonstrates this:
Stream numbers = Stream.of(7,3,9,6,1);
Stream output = numbers.filter(num–> num > 5);
This code creates a Stream of some Integer values. It then
invokes the filter() method with a lambda expression that
checks if the input number is greater than 5. So, the output
Stream will only consist of those numbers that are greater than 5.
Explain the types of Stream operations.
Answer:
Stream operations can be categorized as follows:
Intermediate: Intermediate operations operate on Streams
and produce a Stream output. Since intermediate operations
produce a Stream, they can be chained to perform a series of
operations. Some examples of intermediate operations are
filter, map, sorted
Terminal: Terminal operations operate on Streams but
produce a non–stream result. So, they can produce a result
of any data type. Terminal operations cannot be chained.
When a number of Stream operations are chained, a terminal
operation is typically the last operation. Some examples of
terminal operations are count, anyMatch, allMatch,
collect

Download 1.52 Mb.

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




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