2

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()));
1
  • Error:(114, 33) java: incompatible types: inference variable K has incompatible bounds equality constraints: java.lang.String lower bounds: java.lang.Object Commented Jan 29, 2018 at 20:24

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow thanks!! I guess I got a bit lost & my mind went in a different direction. Is it ok to typecast like this : (String)map.get("group_id") ?
@GauravSaini how about proving the correct types initially?
'@Eugene my expected key needs to be a String type and I am less keen to keep keys open ended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.