Given:
class Student {
String course, name, city;
public Student(String name, String course, String city) {
this.course = course;
this.name = name;
this.city = city;
}
public String toString() {
return course + ":" + name + ":" + city;
}
public String getCourse() {
return course;
}
}
and the code fragment:
List<Student> stds = Arrays.asList(
new Student("Jessy", "Java ME", "Chicago"),
new Student("Helen", "Java EE", "Houston"),
new Student("Mark", "Java ME", "Chicago"));
stds.stream()
.collect(Collectors.groupingBy(Student::getCourse))
.forEach((src, res) -> System.out.println(src));
What is the result?
A.
[Java EE: Helen:Houston]
[Java ME: Jessy:Chicago, Java ME: Mark:Chicago]
B.
[Java ME: Jessy:Chicago, Java ME: Mark:Chicago]
Java EE
Java ME
C.
Java ME
[Java ME: Jessy:Chicago, Java ME: Mark:Chicago]
[Java EE: Helen:Houston]
D. A compilation error occurs.
[Java EE: Helen:Houston]
題解
程式第45行,串流物件的collect方法可以將串流物件再轉成別的Collection物件,配合Collectors類別的groupingBy方法可以將串流物件中的元素群組化,轉成Map物件。群組化的依據為串流物件的Country物件元素之呼叫getCourse方法後的回傳內容,這個會作為Map的Key值。至於Map的Key值所對應的元素,即為原先的物件。
因此最後產生的Map集合物件,「Java ME」這個課程有「Java ME:Jessy:Chicago」和「Java ME:Mark:Chicago」,而「Java EE」這個課程下只有「Java EE:Helen:Houston」。至於元素在Map物件中的順序,愈先建立群組的項目會排在愈後面,所以「Java ME」會排在「Java EE」之後。元素在List物件中的順序就是原先集合物件的走訪順序,所以「Java ME:Jessy:Chicago」在「Java ME:Mark:Chicago」之前。
程式第46行,只會輸出Map集合物件的key值,因此答案是選項B。