一. 題目
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]}
二. 題解
先把 3個 Country物件放入 couList,
couList轉成 stream流,再使用 stream物件的 collect方法,把 stream物件轉成 Collection物件,
使用 Collectors類別的 groupingBy方法,會回傳一個 Map,
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
第一個參數,使用 Country::getRegion,取得 region,依序是 Asia、Europe,
第二個參數,使用 Collectors.mapping方法,將 stream物件元素,Country物件呼叫 getName方法,回傳的字串會依據相同的 region,組合成一個 List物件,
第一個 List為 [Japan],第二個 List為[Italy, Germany]。
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
輸出結果
答案是B. {ASIA = [Japan], EUROPE = [Italy, Germany]}
三. 參考
[OCPJP]串流與Lambda的精簡應用