2015-01-15 66 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()) 

這將返回一個下游收集器,它將實現你想要的。