Gaurav Saini
Gaurav Saini

Reputation: 752

Convert List<Map<String, Object>> to Map<String, List<Map<String, Object>>> using Java 8 streams API

My question is little similar to what has already been asked here in stackoverflow. My input is as follows:

Map<String, Object> m1 = new HashMap<>();
m1.put("group", "1");
m2.put("A", 10l);
m2.put("B", 20l);
m2.put("C", 100l);

Map<String, Object> m2 = new HashMap<>();
m1.put("group", "1");
m2.put("A", 30l);
m2.put("B", 40l);
m2.put("C", 500l);

List<Map<String, Object>> beforeFormatting = new ArrayList<>();
beforeFormatting.add(m1);
beforeFormatting.add(m2);

My expected output is:

Map<String, List<Map<String, Object>>> afterFormatting;

Output:

1 -> [m1, m2]

I have tried below, but getting compile errors: seems like I am doing something wrong with mapping:

Map<String, List<Map<String, Object>>> afterFormatting = beforeFormatting.stream()
                    .collect(groupingBy(map -> map.get("group_id"), toList()));

Upvotes: 2

Views: 1399

Answers (1)

Eugene
Eugene

Reputation: 121088

Well map.get("group_id") returns an Object, but you try to map it to a String, change the return type:

Map<Object, List<Map<String, Object>>> afterFormatting = beforeFormatting.stream()
            .collect(Collectors.groupingBy(map -> map.get("group_id")));

And also you can drop toList, since it is implicitly used when groupingBy with a single parameter is used.

Upvotes: 2

Related Questions