3

I have a List<Map<String,Object>>

[ {key1: object1a, key2: object2a, key3: object3a}, 
  {key1: object1a, key2: object2a, key3: object3a}, 
  {key1: object1b, key2: object2b, key3: object3b}, 
  {key1: object1b, key2: object2b, key3: object3b}, 
  ...
]

and I would like to group it by the third value, to obtain a Map<String,List<Map<String,Object>>>:

{ object3a: [ {key1: object1a, key2: object2a}, 
              {key1: object1a, key2: object2a}
            ],
  object3b: [ {key1: object1b, key2: object2b}, 
              {key1: object1b, key2: object2b}
            ],
  ...
}

Is it possible by using the Collectors.groupingBy? method, and how ?

5
  • It isn't really clear to me what you are grouping your data by in your example. Commented Mar 3, 2015 at 2:30
  • At first you seemed to be using a JSON-like notation, with lists denoted by [...] and maps by {...} . . . but then I got to [sample1: a, sample2 : b], and I suddenly have no idea what notation you're using. Commented Mar 3, 2015 at 2:39
  • I have a list [{sample1 : a, sample2: b, sample3:c}, {sample1 : b, sample2: d, sample3:c}, ...]. And I would like to group by sample3 : key c by using Collectors.groupingby method to get a map like this { c : [{sample1: a, sample2: b}, {sample1: b, sample2 : d},..]. Is it really possible by using Collectors.groupingby? Commented Mar 3, 2015 at 3:45
  • Please write a clear code example. Commented Mar 3, 2015 at 6:16
  • @AungSatt I've rewritten your example in a more understandable shape. Please confirm that this is what you want to achieve Commented Mar 3, 2015 at 11:38

1 Answer 1

5

The request isn’t a pure grouping operation as you want to modify the elements by removing the grouping value.

If the maps are mutable, it’s still possible and quite easy:

List<Map<String,String>> list= …
Map<String,List<Map<String,String>>> map=
  list.stream().collect(Collectors.groupingBy(m->m.remove("key3")));

Note that I use the key "key3" here which matches the current revision of the question. To adapt it to your original question, you have to replace "key3" with "sample3".

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

Comments

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.