2016-04-25 16 views
2

私のオブジェクトにリストとして表示される値でグループ化しようとしています。Javaストリーム - キーがリストに表示されたときのグループ化

これは私が次でそれを初期化すると、私は

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()))); 

しかし、私はそれを完了するのに苦労しています。元の生徒をマッピングした後もどうしたらいいですか?上記のコメントをまとめる

+4

「Map >」である必要があります。また、あなたは 'Tuple'クラスを表示していませんが、' Entry :: getValue'はあなたが望むものではないと思われます。私は 'y - > y.getStudent()'に行きます。そして、それは動作します:)。 – Tunaki

答えて

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()))); 

を別の方法として、あなただけのその場所を含む各リストで生徒を気にしないならば、あなたは学生を平らに検討するかもしれません1つの場所のみの生徒にリストする:

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))); 
関連する問題