![](/img/trans.png)
[英]Convert Map<Integer, List<Object>> to Map<Integer, Map<String, Map<LocalDate, Integer>>> using Java stream API
[英]Java Stream Grouping by List<Map<String, Object>> to Map<Integer, List<Integer>>
我有一个
List<Map<String, Object>>
来自Spring NamedParameterJdbcTemplate queryForList调用。 数据返回如下所示:
[{"id":5,"uid":6}, {"id":5,"uid":7}, {"id":6,"uid":8}, {"id":7,"uid":7}, {"id":8,"uid":7}, {"id":8,"uid":9}]
如何按以下格式重新排列数据?
{5:[6, 7], 6:[8], 7:[7], 8:[7, 9]}
我希望返回Map<Integer, List<Integer>>
任何人都知道如何实现这一目标? 任何帮助非常感谢?
这是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())));
或根本没有溪流:
list.forEach(x -> {
Integer key = (Integer) x.get("id");
Integer value = (Integer) x.get("uuid");
result.computeIfAbsent(key, ignoreMe -> new ArrayList<>()).add(value);
});
您可以在使用分组收集器时将键和值映射到整数:
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())));
使用((Number) map.get("id")).intValue()
以防万一值为Long。
我不是流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; 我只是认为这比收集器和下游收集器的所有问题更令人愉快,并且当你犯类型错误时会出现非明显的错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.