Java 8 Java流-当键出现在列表中时按分组

Java 8 Java流-当键出现在列表中时按分组,java-8,java-stream,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) { thi

我正在尝试按一个集合按一个值分组,该值在我的对象中显示为列表

这就是我的模型

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));
  }
}
我试着写以下内容

  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())));
Map x=studlist.stream()
.flatMap(student->student.getStud_location().stream().map(loc->new Tuple(loc,student)))
.collect(Collectors.groupingBy(y->y.getLocation(),映射(Entry::getValue,toList());

但我在完成它时遇到了困难-在绘制地图后,我如何保留原始学生?

总结上述评论,收集的智慧建议:

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 x=studlist.stream()
.flatMap(student->student.getStud_location().stream().map(loc->newAbstractMap.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)));
Map x=studlist.stream()
.flatMap(学生->
student.stud_location.stream().map(loc->
新学生(Student.stud\u id、Student.stud\u name、loc))
).collect(Collectors.groupingBy(student->student.stud_location.get(0));
它应该是
Map
。另外,您还没有显示
Tuple
类,但我怀疑
Entry::getValue
不是您想要的。我会选择
y->y.getStudent()
。它是有效的:)。
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)));