Java Stream Grouping by List<Map<String, Object>> to Map<Integer, List<Integer>>

DMcg :

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??

ernest_k :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112454&siteId=1