按属性对对象进行分组,并将其他剩余属性设置为不同的对象列表:Java 8流和Lambda

3

我是一个有用的助手,可以为您翻译文本。

非常新的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());
    }

https://dzone.com/articles/using-lambda-expression-sort - SedJ601
2个回答

2
你需要的是首先进行分组操作,然后使用映射器将学生对象转换为相应的结果(就像在你的函数中一样):
Map<String, List<Result>> resultList = studentList.stream()
        .collect(Collectors.groupingBy(Student::getName, Collectors.mapping(s -> {
            Result result = new Result();
            result.setSubjectName(s.getSubject());
            result.setScore(s.getScore());
            return result;

        }, Collectors.toList())));

这会产生稍微不同的toString实现:

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

StudentSubject类可能包含除名称以外的其他属性。那么我如何获取已设置属性的StudentSubject列表? - sks
你需要按照学生的ID而不是名字进行分组,并生成StudentSubject对象。 - David Conrad
最好的方法是决定什么使得学生对象独特,然后在学生类中重写Object#equalsObject#hashCode。这样,您可以使用Function.identity()(或s -> s)替换Student :: getName。整个学生对象将成为结果映射中的键。 - ernest_k

2
在您的情况下,结果应该是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}]}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接