Lista de grupos de objetos por un atributo y un conjunto otro atributo restante a diferentes lista de objetos: Java 8 arroyo y Lambdas

créditos:

Muy nuevo para Java8 corriente / Lambdas. Necesito una lista de grupo Estudiante objetos utilizando un atributo (Id) a continuación, crear el objeto (StudentSubject) basado en los atributos de los estudiantes agrupados. Por ejemplo, tengo siguientes clases:

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
    }

Así que para la entrada siguiente:

id,name,subject,score  
1,John,Math,80
1,John,Physics,65
2,Thomas,Computer,55
2,Thomas,Biology,70

La salida resultado debe ser List<StudentSubject>con atributos establecidos desde el List<Student>. Decir algo como:

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}, 
        ]

¿Cómo puedo agrupar por Id primero y luego establecer los atributos de resultado y 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());
    }
YCF_L:

El resultado debe ser List<StudentSubject>en su caso se puede usar de esta manera:

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

salidas

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}]}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=204754&siteId=1
Recomendado
Clasificación