2015-01-15 69 views
18

List<Map<String, String>>列表中的每个项目是地图如Java的8个流groupingby

companyName - IBM 
firstName - James 
country - USA 
... 

我想创造一个Map<String, List<String>>它映射的companyName到列表的firstName 如

IBM -> James, Mark 
ATT -> Henry, Robert.. 


private Map<String,List<String>> groupByCompanyName(List<Map<String, String>> list) { 
    return list.stream().collect(Collectors.groupingBy(item->item.get("companyName"))); 
} 

但这会创建Map<String, List<Map<String, String>>(将comanyName映射到地图列表)

如何创建一个Map<String, List<String>>

回答

29

没有测试过,但这样的事情应该工作:

Map<String, List<String>> namesByCompany 
    = list.stream() 
      .collect(Collectors.groupingBy(item->item.get("companyName"), 
        Collectors.mapping(item->item.get("firstName"), Collectors.toList()))); 
+0

有什么办法可以得到'String []'而不是'List ' – 2017-12-04 09:30:18

+1

我不这么认为(至少不是直接),因为没有'Collectors.toArray'方法。 @VinitSolanki – Eran 2017-12-04 09:42:33

5

可以使用以下形式:

groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream) 

即,从在下游地图可以被视为列表中指定的值。该文档有很好的例子(here)。

downstream是类似 - mapping(item->item.get(<name>), toList())

0

的groupingBy方法产生一个映射,其值列表。如果您想以某种方式处理这些列表,请提供一个“下游收集器” 在您的情况下,您不需要列表作为值,因此您需要提供下游收集器。

要操作地图,可以使用静态方法映射在收藏家文件:

Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, 
          Collector<? super U, A, R> downstream) 

它基本上通过将函数应用于所述下游结果产生一个集电极和传递函数到另一个收集器。

Collectors.mapping(item->item.get("firstName"), Collectors.toList()) 

这将返回一个下游收集器,它将实现你想要的。