Java将列表转换为集合映射

时间:2017-09-19 22:34:46

标签: java lambda java-8 java-stream

假设我有一个名为Student的对象列表。对象学生的定义如下

public Class Student {
    private String studentName;
    private String courseTaking;
}

在学生列表中,可以有多个学生对象具有相同的studentName但不同的courseTaking。现在我想将学生列表转换为studentName和courseTaking的地图,如此

Map<String, Set<String>>

关键是studentName,并且该值是同一个学生的所有课程。我怎么能用stream()和amp;收集()?

1 个答案:

答案 0 :(得分:5)

我认为这就是你要找的东西:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


public class StackOverflow {

  private static class SO46310655 {
    public static void main(String[] args) {
      final List<Student> students = new ArrayList<>();
      students.add(new Student("Zoff", "Java 101"));
      students.add(new Student("Zoff", "CompSci 104"));
      students.add(new Student("Zoff", "Lit 110"));
      students.add(new Student("Andreas", "Kotlin 205"));
      Map<String, Set<String>> map = students.stream().collect(
          Collectors.groupingBy(
              Student::getStudentName,
              Collectors.mapping(
                  Student::getCourseTaking,
                  Collectors.toSet()
              )
          )
      );
      System.out.println(map);
    }

    public static class Student {
      private final String studentName;
      private final String courseTaking;

      public Student(String studentName, String courseTaking) {
        this.studentName = studentName;
        this.courseTaking = courseTaking;
      }

      public String getStudentName() {
        return studentName;
      }

      public String getCourseTaking() {
        return courseTaking;
      }
    }
  }
}

yeilds {Andreas=[Kotlin 205], Zoff=[Java 101, CompSci 104, Lit 110]}