Java 8 lambdas group list into map(Java 8 lambdas 将列表分组到地图中)
问题描述
我想取一个 List<Pojo> 和 return 一个 Map<String, ListMap的key是Pojo中的String值,我们称之为String key.
I want to take a List<Pojo> and return a Map<String, List<Pojo>> where the Map's key is a String value in Pojo, let's call it String key.
为了澄清,给出以下内容:
To clarify, given the following:
Pojo 1:键:值:1
Pojo 1: Key:a value:1
Pojo 2:键:值:2
Pojo 2: Key:a value:2
Pojo 3:键:b 值:3
Pojo 3: Key:b value:3
Pojo 4:键:b 值:4
Pojo 4: Key:b value:4
我想要一个 Map<String, List<Pojo>>,其中 keySet() 大小为 2,其中键a"具有 Pojos 1 和 2,并且键"b" 有 pojos 3 和 4.
I want a Map<String, List<Pojo>> with keySet() sized 2, where key "a" has Pojos 1 and 2, and key "b" has pojos 3 and 4.
我怎样才能最好地使用 Java 8 lambdas 实现这一点?
How could I best achieve this using Java 8 lambdas?
推荐答案
看来简单的 groupingBy 变体就是你需要的:
It seems that the simple groupingBy variant is what you need :
Map<String, List<Pojo>> map = pojos.stream().collect(Collectors.groupingBy(Pojo::getKey));
这篇关于Java 8 lambdas 将列表分组到地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 lambdas 将列表分组到地图中
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
