gpt4 book ai didi

java - 按属性对对象列表进行分组并将其他剩余属性设置为不同的对象列表 : Java 8 stream and Lambdas

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:23 25 4
gpt4 key购买 nike

Java8 流/Lambda 的新手。我需要使用属性 (Id) 对学生对象列表进行分组,然后根据分组的学生属性创建对象 (StudentSubject)。例如我有以下类(class):

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<StudentSubject>具有从 List<Student> 设置的属性.说点什么:

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 分组,然后将属性设置为 Result 和 StudentSubject?

     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());
}

最佳答案

结果应该是List<StudentSubject>在您的情况下,您可以使用这种方式:

List<StudentSubject> resultList = studentList.stream()
.collect(Collectors.groupingBy(Student::getId)) // until this point group by Id
.entrySet() // for each entry
.stream()
.map(s -> new StudentSubject( // create a new StudentSubject
s.getValue().get(0).getName(), // you can use just the name of first element
s.getValue().stream() // with a list of Result
.map(r -> new Result(r.getSubject(), r.getScore()))
.collect(Collectors.toList()))
).collect(Collectors.toList()); // then collect every thing as a List

输出

StudentSubject{name='John', results=[Result{subjectName='Math', score=80}, Result{subjectName='Physics', score=65}]}
StudentSubject{name='Thomas', results=[Result{subjectName='Computer', score=55}, Result{subjectName='Biology', score=70}]}

关于java - 按属性对对象列表进行分组并将其他剩余属性设置为不同的对象列表 : Java 8 stream and Lambdas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51620501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com