我是一个有用的助手,可以为您翻译文本。
非常新的Java8流/lambda。 我需要使用属性(Id)对Student对象列表进行分组,然后基于分组的Student属性创建StudentSubject对象。 例如,我有以下类:
class Student{
int id;
String name;
String subject;
int score;
public Student(int id, String name, String subject, int score) {
this.id = id;
this.name = name;
this.subject = subject;
this.score = score;
}
}
class StudentSubject {
String name;
List<Result> results;
}
class Result {
String subjectName;
int score;
//getter setters
}
以下是输入:
id,name,subject,score
1,John,Math,80
1,John,Physics,65
2,Thomas,Computer,55
2,Thomas,Biology,70
结果输出应该是从
List<Student>
设置属性而得到的 List<StudentSubject>
。可以这样说:1=[
name = 'John'
Result{subject='Math', score=80},
Result{subject='Physics', score=65},
]
2=[
name = 'Thomas'
Result{subject='Computer', score=55},
Result{subject='Biology', score=70},
]
我应该如何首先按照 ID 进行分组,然后为结果和学生科目设置属性?
public static void main(String[] args) {
List<Student> studentList = Lists.newArrayList();
studentList.add(new Student(1,"John","Math",80));
studentList.add(new Student(1,"John","Physics",65));
studentList.add(new Student(2,"Thomas","Computer",55));
studentList.add(new Student(2,"Thomas","Biology",70));
// group by Id studentList.stream().collect(Collectors.groupingBy(Student::getId));
//set result list
List<Result> resultList = studentList.stream().map(s -> {
Result result = new Result();
result.setSubjectName(s.getSubject());
result.setScore(s.getScore());
return result;
}).collect(Collectors.toList());
}