【问题标题】:How to convert List<Object> to Map<String , List<String>> using java 8 streams?如何使用 java 8 流将 List<Object> 转换为 Map<String 、 List<String>>?
【发布时间】:2019-11-25 11:34:45
【问题描述】:

我有 Employee 对象,它有如下的 rowId、skillId 和 student

[0, 20,"John"],

[1, 30,"Amy"],

[2, 20,"Tom"]

我需要这样的回应:

Map<skillId, List<student>>

20 , ["John","Tom"]

30 , [Amy]

谁能帮忙?

【问题讨论】:

  • list.stream().collect(Collectors.groupingBy(Employee::getSkillId,Collectors.mapping(Employee:getStudent,Collectors.toList())));
  • 到目前为止你有什么尝试?

标签: java java-8 java-stream


【解决方案1】:

尝试使用groupingBymapping

list.stream()
     .collect(Collectors.groupingBy(Employee::getSkillId,
                    Collectors.mapping(Employee:getStudent, Collectors.toList())));

【讨论】:

  • 它正在工作,但有 1 个问题,因为它正在返回 map> 但我的方法返回 map> Map> SkillAndList = 新哈希映射(); SkillAndList = employeeList.stream() .collect(Collectors.groupingBy(Employee::getSkillSet, Collectors.mapping(Employee::getUser, Collectors.toList())));因此将响应分配给 SkillAndList 是不兼容的
【解决方案2】:

请使用下面的,

Map<Integer, List<Employee>> collect = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getSkillId, Collectors.toList()));

【讨论】:

    【解决方案3】:
    Map<Integer, List<String>> skillAndList = list.stream().collect(Collectors.groupingBy(Employee::getSkillId, Collectors.mapping(Employee::getStudent, Collectors.toList())));
    System.out.println(skillAndList);
    

    输出和你预期的一样——

    {30=[Amy], 20=[John,Tom]}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多