Java Stream - 当密钥出现在列表中时分组 [英] Java Stream - group by when key appears in a list

查看:117
本文介绍了Java Stream - 当密钥出现在列表中时分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照我的对象中显示的值作为列表对集合进行分组。

I am trying to group by a collection by a value that appears in my object as a list.

这是我拥有的模型

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

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

When I initialize it with the following :

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

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

But I am having trouble completing it - how do I keep the original student after the mapping?

推荐答案

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

Summing up the comments above, the collected wisdom would suggest:

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

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

As an alternate approach, if you don't mind the Students in each list containing only that location, you might consider flattening the Student list to Students with only one location:

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

这篇关于Java Stream - 当密钥出现在列表中时分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆