Java Stream - Gruppieren nach, wenn der Schlüssel in einer Liste angezeigt wird
Ich versuche, eine Sammlung nach einem Wert zu gruppieren, der in meinem Objekt als Liste angezeigt wird.
Dies ist das Modell, das ich habe
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));
}
}
Wenn ich es mit folgendem initialisiere:
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"));
Ich möchte Folgendes erhalten:
California -> Student(1726),Student(4321),Student(2234),Student(7765)
New York -> Student(1726),Student(5223),Student(3442)
Los Angeles => Student(2234)
Ich versuche folgendes @ zu schreib
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())));
Aber ich habe Probleme beim Ausfüllen - wie behalte ich den ursprünglichen Schüler nach dem Mapping?