2016-04-25 82 views
2

我想按集合中出現在我的對象中的值作爲列表進行分組。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()))); 

但是我無法完成它 - 如何在映射後保留原始學生?

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

作爲一種替代方法,如果你不介意在每個列表中只包含該位置的學生,可以考慮壓扁學生列表給只有一個位置的學生:

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