获取嵌套散列表中集合的大小?
问题描述:
我有Map<String, Map <String, List<ExciseReportDataPoint>>> Data
类型的数据结构我想计算每个顶级密钥的List<ExciseReportDataPoint>
的条目数。获取嵌套散列表中集合的大小?
我们可以用逻辑的方式来思考hashmap,如Map<LiquorCategory, Map<LiquorBrand, List<LiquorBottles>>>
。基本上我想知道每个酒类有多少个酒瓶。
答
你必须遍历第一级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线同 流是一种替代和循环过滤器,求和,计数...
答
我根据基于一些答案的建议编写了以下代码。这对我有用。代码如下所示:
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();
}
}
答
地图<字符串,地图<字符串,列表<双>>>数据=新的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();
// ...
}
}
您预计自己尝试代码并询问你是否遇到问题。如果你不尝试自己,我们不会为你写代码。 –
我同意如何解决这个问题? –
map.get(LiquorCategory).size()? –