close

一. 題目

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;
}
}
view raw OCP_15_1.java hosted with ❤ by GitHub

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);
view raw OCP_15_2.java hosted with ❤ by GitHub

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,

image 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]。

image https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

image 輸出結果

答案是B. {ASIA = [Japan], EUROPE = [Italy, Germany]}

 

三. 參考

[OCPJP]串流與Lambda的精簡應用

 

 

arrow
arrow
    文章標籤
    Java OCP 1Z0-809
    全站熱搜
    創作者介紹
    創作者 書童 的頭像
    書童

    小書童

    書童 發表在 痞客邦 留言(0) 人氣()