[英]Java Stream Grouping by List<Map<String, Object>> to Map<Integer, List<Integer>>
I have a 我有一个
List<Map<String, Object>>
coming from a Spring NamedParameterJdbcTemplate queryForList call. 来自Spring NamedParameterJdbcTemplate queryForList调用。 The data return looks like this:
数据返回如下所示:
[{"id":5,"uid":6}, {"id":5,"uid":7}, {"id":6,"uid":8}, {"id":7,"uid":7}, {"id":8,"uid":7}, {"id":8,"uid":9}]
How can I rearrange the data in the following format? 如何按以下格式重新排列数据?
{5:[6, 7], 6:[8], 7:[7], 8:[7, 9]}
Im looking to return a Map<Integer, List<Integer>>
我希望返回
Map<Integer, List<Integer>>
Anyone have an idea how I can achieve this? 任何人都知道如何实现这一目标? Any help much appreciated??
任何帮助非常感谢?
This is a job for Collectors.groupingBy
with a downstream collector like Collectors.mapping
这是
Collectors.groupingBy
一个工作,它有一个下游收集器,如Collectors.mapping
Map<Integer, List<Integer>> result = l.stream()
.collect(Collectors.groupingBy(
m -> (Integer) (m.get("id")),
Collectors.mapping(m -> (Integer) m.get("uuid"), Collectors.toList())));
Or without streams at all: 或根本没有溪流:
list.forEach(x -> {
Integer key = (Integer) x.get("id");
Integer value = (Integer) x.get("uuid");
result.computeIfAbsent(key, ignoreMe -> new ArrayList<>()).add(value);
});
You can map keys and values to integers while using a grouping-by collector: 您可以在使用分组收集器时将键和值映射到整数:
List<Map<String, Object>> maps = null;
Map<Integer, List<Integer>> result = maps.stream()
.collect(Collectors.groupingBy(
map -> ((Number) map.get("id")).intValue(),
Collectors.mapping(map -> ((Number) map.get("uid")).intValue(),
Collectors.toList())));
Using ((Number) map.get("id")).intValue()
just in case the value is a Long. 使用
((Number) map.get("id")).intValue()
以防万一值为Long。
I am not a huge fan of the syntax of the streams API: I think it might be easier to do using a plain old loop (with a few other Java 8-isms): 我不是流API语法的忠实粉丝:我认为使用普通的旧循环(使用其他一些Java 8-isms)可能更容易:
Map<Integer, List<Integer>> result = new HashMap<>();
for (Map<String, Object> entry : list) {
int id = (Integer) entry.get("id");
int uid = (Integer) entry.get("uid");
result.computeIfAbsent(id, k -> new ArrayList<>())
.add(uid);
}
YMMV, of course; 当然是YMMV; I just think this is more pleasant than all of the faffing around with collectors and downstream collectors, and the non-obvious error messages when you make type errors.
我只是认为这比收集器和下游收集器的所有问题更令人愉快,并且当你犯类型错误时会出现非明显的错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.