Java SE 8 Programmer II Exam - Question 1Z0-809 Answer

Java SE 8 Programmer II Exam - Question 1Z0-809 Answer

Question

Given the definition of the Country class: public class country { public enum Continent {ASIA, EUROPE} String name; Continent region; public Country (String na, Continent reg){ name = na, region = reg; } public String getName () {return name;} public Continent getRegion () {return region;} } and the code fragment: List<Country> couList = Arrays.asList ( new Country ("Japan", Country.Continent.ASIA), new Country ("Italy", Country.Continent.EUROPE), new Country ("Germany", Country.Continent.EUROPE)); Map<Country.Continent, List<String>> regionNames = couList.stream () .collect(Collectors.groupingBy (Country ::getRegion, Collectors.mapping(Country::getName, Collectors.toList())))); System.out.println(regionNames);

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The code creates a list of Country objects named couList and initializes it with three elements. It then uses the stream() method to create a stream of the couList and applies the groupingBy collector with a mapping collector to create a Map<Country.Continent, List<String>> object named regionNames.

The groupingBy collector groups the Country objects in couList based on their region attribute, which is of type Country.Continent, and returns a map with Country.Continent as the key and a list of the country names as the value.

The mapping collector is then used to convert the list of Country objects to a list of their names. The toList() method is called on this mapping collector to produce a list of country names.

Finally, the System.out.println(regionNames) statement prints the resulting map to the console.

So, the correct answer is B. The resulting map will have two entries, with the key-value pairs as follows: {ASIA=[Japan], EUROPE=[Italy, Germany]}. This is because the groupingBy collector groups the Country objects by their region attribute, and there are two regions - ASIA and EUROPE. The mapping collector is then used to convert the list of Country objects to a list of their names, resulting in a map that lists the countries in each region. Therefore, option B is the correct answer.