Java OCA OCP Practice Question 3013

Question

Choose the correct option based on this program:

import java.util.stream.Stream;

public class Main {
    public static void main(String []args) {
        Stream<String> words = Stream.of("one", "two", "three");
         int len = words.mapToInt(String::length).reduce(0, (len1, len2) ->
         len1 + len2);//from   w  ww .ja v a 2  s. c o m
        System.out.println(len);
    }
}
a)  this program does not compile and results in compiler error(s)
b)  this program prints: onetwothree
c)  this program prints: 11
d)  this program throws an IllegalArgumentException


c)

Note

this program compiles without any errors.

the variable words point to a stream of Strings.

the call mapToInt(String::length) results in a stream of Integers with the length of the strings.

one of the overloaded versions of reduce() method takes two arguments:.

T reduce(T identity, BinaryOperator<T> accumulator);

the first argument is the identity value, which is given as the value 0 here.

the second operand is a BinaryOperator match for the lambda expression (len1, len2) -> len1 + len2.

the reduce() method thus adds the length of all the three strings in the stream, which results in the value 11.




PreviousNext

Related