Java SE 8 Programmer II Exam: Question Analysis

Analysis of Java SE 8 Programmer II Exam: Question

Question

Given the code fragment: Stream<List<String>> iStr= Stream.of ( Arrays.asList ("1", "John"), Arrays.asList ("2", null)); Stream<<String> nInSt = iStr.flatMapToInt ((x) -> x.stream ()); nInSt.forEach (System.out :: print); What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

D.

The code fragment creates a Stream of Lists of Strings, and then uses the flatMapToInt method to flatten the Stream of Lists into a Stream of Strings. Finally, it prints the result to the console.

Let's analyze the code step by step:

java
Stream<List<String>> iStr = Stream.of(Arrays.asList("1", "John"), Arrays.asList("2", null));

This line creates a Stream of Lists of Strings. The Stream contains two Lists: ["1", "John"] and ["2", null].

java
Stream<String> nInSt = iStr.flatMapToInt((x) -> x.stream());

This line uses the flatMapToInt method to flatten the Stream of Lists into a Stream of Strings. The flatMapToInt method applies the given function to each element of the Stream, and then concatenates the resulting Streams into a single Stream. In this case, the function x -> x.stream() is applied to each List element of the Stream, which returns a Stream of Strings for each List. The resulting Stream is then flattened into a single Stream of Strings.

java
nInSt.forEach(System.out::print);

This line prints each element of the Stream to the console, using a method reference to System.out::print.

Therefore, the output of the code fragment is:

1John2null

The answer is A.