I have a nested hash-map as
HashMap<Integer, HashMap<String,Integer>> productAdded = new HashMap<>();
I added value as
int price=12;
String name="Apple";
productAdded.put(1, new HashMap(){{ put(name, price); }});
and I am trying to retrieve it as
for(int i=1;i<=ProductList.productAdded.size();i++)
{
System.out.println(ProductList.productAdded.get(i).keySet()+"\t :$"+ProductList.productAdded.get(i).values());
}
Actual output
[Large Pizza] :$[12]
Expected output.
Large Pizza :$12
Use for each loop for iterating
for(Integer i :productAdded.keySet()) {
for(String s: productAdded.get(i).keySet()) {
System.out.println(s+"\t :$"+ProductList.productAdded.get(i).get(s));
}
}
You can also do this by using 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));
});
});
Both keySet()
and values()
return collections, hence the additional braces. For your particular case, refactor to keySet().iterator().next()
and values().iterator().next
to achieve the desired output format.
Although not recommended, you can do something like this:
ProductList.productAdded.get(i).keySet().toString().replace("[","").replace("]","");
Same for the values bit.
or you can do something like this:
String brackets = "[\\[\\]]";
ProductList.productAdded.get(i).keySet().toString().replaceAll(brackets,"");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.