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.
B.
C.
D.
題解
程式第 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」之前。
