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);

What is the output?

A.

{EUROPE = [Italy, Germany], ASIA = [Japan]}

B.

{ASIA = [Japan], EUROPE = [Italy, Germany]}

C.

{EUROPE = [Germany, Italy], ASIA = [Japan]}

D.

{EUROPE = [Germany], EUROPE = [Italy], ASIA = [Japan]}

题解

程序第 43 行,取得 couList 清单对象的串流对象。

程序第 44 和 45 行,串流对象的 collect 方法可以将串流对象再转成别的 Collection 对象,配合 Collectors 类别的 groupingBy 方法可以将串流对象中的元素群组化,转成 Map 对象。群组化的依据为串流对象的 Country 对象元素之调用 getRegion 方法后的回传内容,这个会作为 Map 的 Key 值。至于 Map 的 Key 值所对应的元素,在这里使用了 Collectors 类别的 mapping 方法,将串流对象的 Country 对象元素之调用 getName 方法后的回传内容转成 List 对象。

因此最后产生的 Map 集合对象,「ASIA」这个地区下只有「Japan」,而「EUROPE」这个地区下有「Italy」和「Germany」。至于元素在 Map 对象中的顺序,groupingBy 方法预设会使用 HashMap 来存放群组,而 HashMap 并不保证元素的顺序,它是由 Key 值的哈希值来决定元素存放的位置,不能用创建群组的先后来判断。这里的 Key 值是枚举(enum),它的哈希值在不同的运行环境下可能会不一样,所以「ASIA」和「EUROPE」的顺序其实没有保证。实际运行这段程序的结果是「ASIA」排在「EUROPE」之后,所以这题选择选项 A 的话会比较合适。元素在 List 对象中的顺序就是原先集合对象的走访顺序,所以「Italy」在「Germany」之前。