Java OCA OCP Practice Question 1983

Question

What is a possible output of the following application?.

package mypkg; //w  w  w  . j  a  va2s . c  o  m
import java.util.*; 
import java.util.concurrent.*; 
import java.util.stream.*; 
public class Main { 
   private String model; 
   private int year; 
   public Main(String name, int year) { 
      this.model = name; this.year = year; 
   } 
   public int getYear() {return year;} 
   @Override public String toString() {return model;} 

   public static void main(String... make) { 
      List<Main> cars = new ArrayList<>(); 
      cars.add(new Main("A",1967)); 
      cars.add(new Main("B",1967)); 
      cars.add(new Main("C",1975)); 
      ConcurrentMap<Integer, List<Main>> map = cars 
         .stream() 
         .collect(Collectors.groupingByConcurrent(Main::getYear)); 
      System.out.print(map); 
   } 
} 
  • A. {1975=[C], 1967=[B, A]}
  • B. {C=[1975], B=[1967], A=[1967]}
  • C. The code does not compile.
  • D. The application throws an exception at runtime because the stream is not parallel.


A.

Note

The code compiles and runs without issue.

The JVM will fall back to a single-threaded process if all of the conditions for performing the parallel reduction are not met.

The stream used in the main() method is not parallel, but the groupingbyConcurrent() method can still be applied without throwing an exception at runtime.

Although performance will suffer from not using a parallel stream, the application will still process the results correctly.

Since the process groups the data by year, Option A is the correct answer.




PreviousNext

Related