I have a
List<Map<String, Object>>
coming from a Spring NamedParameterJdbcTemplate queryForList call. 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>>
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
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With