2016-11-02 95 views
4

轉化的模式列表進入地圖與地圖內我有一個List<Model>使用Java 8流

[ 
    {parent: "parent", child: "child1", sensor: "wohoo"}, 
    {parent: "parent", child: "child1", sensor: "bla"}, 
    {parent: "parent", child: "child2", sensor: "wohoo2"} 
] 

,我想將其轉換爲地圖<String, Map<String, List<String>>>

{ 
    parent: { 
    child1: ["wohoo", "bla"], 
    child2: ["wohoo2"] 
    }, 
} 

我已經試過這樣:

Map<String, Map<String, List<String>>> test = currentlyReportingAgents 
     .stream() 
     .collect(Collectors.groupingBy(
     Model::getParent, 
     Collectors.groupingBy(Model::getChild, Collectors.toList()))); 

但有一些有線編譯錯誤..我在想什麼?

編輯:添加了錯誤的截圖: enter image description here

+2

請在您的問題編譯錯誤。 – khelwood

回答

3

您的解決方案將返回不同的類型:

Map<String, Map<String, List<Model>>> = ...; 

達到你想要什麼,你需要打開一個List<Model>List<String>mapping(mapper, downstream)

Map<String, Map<String, List<String>>> r = currentlyReportingAgents.stream() 
    .collect(groupingBy(Model::getParent, 
         groupingBy(Model::getChild, mapping(Model::getChild, toList())))); 
+0

不錯。添加一個'r.forEach((k,v) - > System.out.println(k +「::」+ v));'這一切都來了。 – mohsenmadi