例如我手邊有 class Student
class Student{
private int studentID, teacherID;
private String studentName;
public Student (int studentID, int teacherID, String studentName){
this.studentID = studentID;
this.teacherID = teacherID;
this.studentName = studentName;
}
public int getStudentID(){return studentID;}
public int getTeacherID(){return teacherID;}
public String getStudentName(){return studentName;}
public String toString(){
return String.format("[Student %02d: %s]", studentID, studentName);
}
}
假設我手邊有學生清單( List<Student>)
但我想看每個老師底下有哪些學生,換言之,想將之轉為 Map< int (teacherID), List<Student>>
作法如下:
import java.util.*;
import java.util.stream.*;
public class Main{
public static void main(String[] args) {
List<Student> list = Arrays.asList(
new Student(1, 100, "andy"),
new Student(2, 100, "bella"),
new Student(3, 200, "Can"),
new Student(4, 100, "Donny")
);
System.out.println(list);
System.out.println(
list.stream()
.collect(
Collectors.groupingBy(
s -> s.getTeacherID(),
Collectors.toList()
)
)
);
}
}
參考資料
Eran, (2018, February 28). java - Grouping by and map value. StackOverflow. https://stackoverflow.com/a/49029481
Fabian, (2019, September 11). java - Grouping by and map value. Stackoverflow. https://stackoverflow.com/a/57897640
沒有留言:
張貼留言