Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 20
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- class Certification {
- String studId;
- String test;
- int marks;
- Certification(String studId, String test, int marks) {
- this.studId = studId;
- this.test = test;
- this.marks = marks;
- }
- public String toString() {
- return "{" + studId + ", " + test + ", " + marks + "}";
- }
- public String getStudId() {
- return studId;
- }
- public String getTest() {
- return test;
- }
- public int getMarks() {
- return marks;
- }
- }
- public class Test {
- public static void main(String[] args) {
- Certification c1 = new Certification("S001", "OCA", 87);
- Certification c2 = new Certification("S002", "OCA", 82);
- Certification c3 = new Certification("S001", "OCP", 79);
- Certification c4 = new Certification("S002", "OCP", 89);
- Certification c5 = new Certification("S003", "OCA", 60);
- Certification c6 = new Certification("S004", "OCA", 88);
- Stream<Certification> stream = Stream.of(c1, c2, c3, c4, c5, c6);
- Map<Boolean, List<Certification>> map =
- stream.collect(Collectors.partitioningBy(s -> s.equals("OCA")));
- System.out.println(map.get(true));
- }
- }
What will be the result of compiling and executing Test class?
- A []
- B [{S001, OCA, 87}, {S002, OCA, 82}, {S001, OCP, 79}, {S002, OCP, 89}, {S003, OCA, 60}, {S004, OCA, 88}]
- C [{S001, OCP, 79}, {S002, OCP, 89}]
- D [{S001, OCA, 87}, {S002, OCA, 82}, {S003, OCA, 60}, {S004, OCA, 88}]
Reveal correct answer
Correct answer: A
Explanation
Rest of the code is very simple, let us concentrate on partitioning code.
Collectors.partitioningBy(s -> s.equals("OCA")) => s in this lambda expression is of Certification type and not String type.
This means predicate 's -> s.equals("OCA")' will return false for "OCA". None of the certification object will return true and hence no element will be stored against 'true'.
[] will be printed in the output.
Correct predicate will be: 's -> s.getTest().equals("OCA")'.
For above predicate, output for 'System.out.println(map.get(true));' will be:
[{S001, OCA, 87}, {S002, OCA, 82}, {S003, OCA, 60}, {S004, OCA, 88}]
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
