Java Stream - 当密钥出现在列表中时分组

时间:2016-04-25 20:53:07

标签: java-8 java-stream

我正在尝试按集合中的值对象进行分组。

这是我的模型

public class Student {
  String stud_id;
  String stud_name;
  List<String> stud_location = new ArrayList<>();

  public Student(String stud_id, String stud_name, String... stud_location) {
      this.stud_id = stud_id;
      this.stud_name = stud_name;
      this.stud_location.addAll(Arrays.asList(stud_location));
  }
}

当我使用以下内容初始化它时:

    List<Student> studlist = new ArrayList<Student>();
    studlist.add(new Student("1726", "John", "New York","California"));
    studlist.add(new Student("4321", "Max", "California"));
    studlist.add(new Student("2234", "Andrew", "Los Angeles","California"));
    studlist.add(new Student("5223", "Michael", "New York"));
    studlist.add(new Student("7765", "Sam", "California"));
    studlist.add(new Student("3442", "Mark", "New York"));

我想得到以下内容:

California -> Student(1726),Student(4321),Student(2234),Student(7765)
New York -> Student(1726),Student(5223),Student(3442)
Los Angeles => Student(2234)

我尝试编写以下内容

  Map<Student, List<String>> x = studlist.stream()
            .flatMap(student -> student.getStud_location().stream().map(loc -> new Tuple(loc, student)))
            .collect(Collectors.groupingBy(y->y.getLocation(), mapping(Entry::getValue, toList())));

但是我无法完成它 - 如何在映射后保留原始学生?

1 个答案:

答案 0 :(得分:1)

总结上述评论,收集到的智慧会暗示:

Map<String, List<Student>> x = studlist.stream()
            .flatMap(student -> student.getStud_location().stream().map(loc -> new AbstractMap.SimpleEntry<>(loc, student)))
            .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, toList())));

作为替代方法,如果您不介意每个列表中仅包含该位置的学生,您可以考虑将学生列表展平给只有一个位置的学生:

Map<String, List<Student>> x = studlist.stream()
        .flatMap( student ->
                student.stud_location.stream().map( loc ->
                        new Student(student.stud_id, student.stud_name, loc))
        ).collect(Collectors.groupingBy( student -> student.stud_location.get(0)));