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

时间:2018-07-31 19:14:06

标签: java java-8 java-stream

对Java8流/ Lambdas来说是新的。我需要使用attribute(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<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());
    }

2 个答案:

答案 0 :(得分: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]]
}

答案 1 :(得分: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}]}