如何分组List <map <string,object>&gt; to map <string,list <map <string,object>&gt;在Java8中</string,list <map <string,object> </map <string,object>

时间:2015-03-03 02:25:54

标签: java java-8 java-stream collectors

我有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}, 
  ...
]

我希望按第三个值对其进行分组,以获得Map<String,List<Map<String,Object>>>

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

是否可以使用Collectors.groupingBy?方法,以及如何使用?

1 个答案:

答案 0 :(得分:4)

请求不是纯分组操作,因为您要通过删除分组值来修改元素。

如果地图是可变的,那么它仍然可能非常简单:

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

请注意,我在这里使用的密钥"key3"与当前版本的问题相匹配。要使其与原始问题相符,您必须将"key3"替换为"sample3"