我有一个嵌套的 HashMap
HashMap<Integer, HashMap<String,Integer>> productAdded = new HashMap<>();
我增加了值(value)
int price=12;
String name="Apple";
productAdded.put(1, new HashMap(){{ put(name, price); }});
我正在尝试将其检索为
for(int i=1;i<=ProductList.productAdded.size();i++)
{
System.out.println(ProductList.productAdded.get(i).keySet()+"\t :$"+ProductList.productAdded.get(i).values());
}
实际输出
[Large Pizza] :$[12]
预期输出。
Large Pizza :$12
最佳答案
使用 for 每个循环进行迭代
for(Integer i :productAdded.keySet()) {
for(String s: productAdded.get(i).keySet()) {
System.out.println(s+"\t :$"+ProductList.productAdded.get(i).get(s));
}
}
您还可以使用 java 8 Streams foreach 来做到这一点
ProductList.productAdded.keySet().stream().forEach(item->{
ProductList.productAdded.get(item).keySet().stream().forEach(inneritem->{
System.out.println(inneritem+"\t :$"+ProductList.productAdded.get(item).get(inneritem));
});
});
关于java - 如何在良好的 View 中从嵌套 HashMap 中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360562/