OCP Question 49, Explanation

Given the code fragment:

List<String> listVal = Arrays.asList("Joe", "Paul", "Alice", "Tom");
System.out.println (
// line n1
);

Which code fragment, when inserted at line n1, enables the code to print the count of string elements whose length is greater than three?

A. listVal.stream().filter(x -> x.length()>3).count()
B. listVal.stream().map(x -> x.length()>3).count()
C. listVal.stream().peek(x -> x.length()>3).count().get()
D. listVal.stream().filter(x -> x.length()>3).mapToInt(x -> x).count()

 

The correct answer is A.

 

Like in the previous Problem, the code fragment compiles successfully, so we turn our attention to the available options. Since the task specifies a certain condition, neither map() nor peek() can help.

Option D does filter out elements whose length exceeds three, but the next stage tries to map these elements – whose type is String – to ints directly. Which, of course, flags a comperr. Changing lambda from x -> x to, say, x -> x.length() would not only make the code compile but also meet the stated requirement.

As for option A, it’s just option D without the offending stage.

Now let’s consider option B: is there any way to salvage it? Oh yes, most definitely; all we’d need is add a filter. For example:

listVal.stream()
.map(x ->  x.length()>3 )
.filter( x -> x == true )
.count()  // 2

What about option C? Well, this one not only misses the objective but is also guilty of violating syntax rules on two counts:

– filter()’s arg is Consumer, so its lambda may not return anything, and
– get() after a terminal operation must obviously operate on an Optional, but count() returns… It returns what? Please don’t tell me you don’t remember what this method returns; we’ve already had an additional question on this subject in Problem 4.

Leave Comment

Your email address will not be published.