2017-02-16 68 views
-2

我有Map<String, Map <String, List<ExciseReportDataPoint>>> Data類型的數據結構我想計算每個頂級密鑰的List<ExciseReportDataPoint>的條目數。獲取嵌套散列表中集合的大小?

我們可以用邏輯的方式來思考hashmap,如Map<LiquorCategory, Map<LiquorBrand, List<LiquorBottles>>>。基本上我想知道每個酒類有多少個酒瓶。

+1

您預計自己嘗試代碼並詢問你是否遇到問題。如果你不嘗試自己,我們不會爲你寫代碼。 –

+0

我同意如何解決這個問題? –

+0

map.get(LiquorCategory).size()? –

回答

1

你必須遍歷第一級Map,然後在第二個來計算所有List.size

第一種方式

Map<String, Map <String, List<Double>>> Data = new HashMap<String, Map <String, List<Double>>>(); 
int somme = 0; 
for(String key1 : Data.keySet()){ 
    somme = 0; 
    for(List<Double> value2 : Data.get(key1).values()){ 
     somme += value2.size(); 
    } 
    System.out.println("For "+key1+", there is "+somme+" bottles"); 
} 

要使用它,你只有改變的類型元素(字符串,與酒的雙重...)

第二種方式

Data.keySet().stream().forEach(key1 -> { 
      System.out.println("For " + key1 + ", there is " 
        + Data.get(key1).values().stream().mapToInt(list -> list.size()).sum() + " bottles"); 
     }); 

在這裏,您不必花費大約類型的醫療服務,他們都沒有用,而且它在3線同 流是一種替代和循環過濾器,求和,計數...

0

我根據基於一些答案的建議編寫了以下代碼。這對我有用。代碼如下所示:

for (Map.Entry<String, Map<String, List<ExciseReportDataPoint>>> entry1 : rData.entrySet()) { 
    int liquorBottle = 0; 
    for(List<ExciseReportDataPoint> value2 : rData.get(entry1.getKey()).values()){ 
     liquorBottle += value2.size(); 
    } 
} 
0

地圖<字符串,地圖<字符串,列表<雙>>>數據=新的HashMap <字符串,地圖<字符串,ArrayList的<雙>>>();

爲(Map.Entry的<字符串,HashMap的<字符串,列表<雙>>> liquorCategoryEntry:data.entrySet()){

String category = liquorCategoryEntry.getKey(); 

int liquorBottle = 0; 
for (Map.Entry<String, List<Double>> liquorBrandEntry : liquorCategoryEntry.getValue().entrySet()) { 
    String brandName = liquorBrandEntry.getKey(); 
    liquorBottle += liquorBrandEntry.getValue().size(); 
    // ... 
} 

}