I want to iterate through a HashMap which is inside another HashMap
Map<String, Map<String, String>> PropertyHolder
I was able to iterate through the parent HashMap as following,
Iterator it = PropertyHolder.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println("pair.getKey() : " + pair.getKey() + " pair.getValue() : " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
but could not able to iterate through the child Map, It can be done by converting pair.getValue().toString() and separated using , and =. Is there any other way of iterating it?
for (Entry<String, Map<String, String>> entry : propertyHolder.entrySet()) {
Map<String, String> childMap = entry.getValue();
for (Entry<String, String> entry2 : childMap.entrySet()) {
String childKey = entry2.getKey();
String childValue = entry2.getValue();
}
}
You could iterate the child map similar to how you've done the parent:
Iterator<Map.Entry<String, Map<String, String>>> parent = PropertyHolder.entrySet().iterator();
while (parent.hasNext()) {
Map.Entry<String, Map<String, String>> parentPair = parent.next();
System.out.println("parentPair.getKey() : " + parentPair.getKey() + " parentPair.getValue() : " + parentPair.getValue());
Iterator<Map.Entry<String, String>> child = (parentPair.getValue()).entrySet().iterator();
while (child.hasNext()) {
Map.Entry childPair = child.next();
System.out.println("childPair.getKey() : " + childPair.getKey() + " childPair.getValue() : " + childPair.getValue());
child.remove(); // avoids a ConcurrentModificationException
}
}
I've presumed you want to call .remove() on the child map, which will lead to a ConcurrentModificationException if done while looping the entrySet - it looks as though you discovered this already.
I've also swapped out your use of casting with strongly-typed generics as suggested in the comments.
It's obvious - you need two nested loops:
for (String key1 : outerMap.keySet()) {
Map innerMap = outerMap.get(key1);
for (String key2: innerMap.keySet()) {
// process here.
}
}
Related
I want to print the keys of my HashMap "allDishes".
This HashMap contains an Dish as the value.
The Dish class has a HashMap field named "Ingredients".
I want to print the key of the "allDishes" and the keys of its HashMap "Ingredients".
With the foreach keySet(),
the key for Ingredients is "null",
because there is no value in "Ingredient" like there is in "allDishes".
Is it possible at all to print keys of different HashMaps?
Map<String, Dish> allDishes = (Map<String, Dish>) application.getAttribute("allDishesHashMap");
for (String key : allDishes.keySet()) {
Map <String, String> Ingredient = allDishes.get(key).getIngredients();
out.println("<li><b>" + key + "</b> with: </li>" + Ingredient.get(key));
}
You are doing it wrong.
Currently,
you are iterating through the keys of the allDishes HashMap.
What you want to do is iterate through the keys of the allDishes HashMap and
for each key in the allDishes HashMap,
iterate through the keys of Ingredient HashMap contained within the current dish in the allDishes HashMap.
To do this,
first iterate through the allDishes entrySet,
then iterate through the ingredients keySet for each entry.
Here is some code:
final Map<String, Dish> dishMap = (Map<String, Dish>)application.getAttribute("allDishesHashMap");
for (final Map.Entry dishEntry: dishMap.entrySet())
{
final Map <String, String> ingredientMap = dishEntry.getIngredients();
out.println("<li><strong>" + dishEntry.getKey() + "</strong> Ingredients: <ul>");
for (final String ingredientName : ingredientMap.keySet())
{
out.println("<li>" + ingredientName + "</li>")
}
out.println("</ul></li>");
}
You can print them with nested loops and a null check.
Map<String, Dish> allDishes = (Map<String, Dish>)
application.getAttribute("allDishesHashMap");
for (String dishKey : allDishes.keySet()) {
Map <String, String> ingredients = allDishes.get(dishKey).getIngredients();
System.out.println("Dish Key: " + dishKey);
// check if null here, if necessary
if (ingredients == null) {
continue; // continue, or print something else. whatever you need
}
for (String ingredient : ingredients.keySet()) {
System.out.println("Ingredient Key: " + ingredient);
}
}
You can also print a "keyset" directly like the following if you don't need any special formatting on the keysets.
Map<String, Dish> allDishes = (Map<String, Dish>)
application.getAttribute("allDishesHashMap");
for (String key : allDishes.keySet()) {
Map <String, String> ingredients = allDishes.get(key).getIngredients();
System.out.println("Dish Key: " + key);
// check if null here, if necessary
if (ingredients == null) {
continue; // continue, or print something else. whatever you need
}
System.out.println("Ingredients KeySet: " + ingredients.keySet());
}
I have a method which returns out hashmap of hashmaps
HashMap<String, HashMap<String, String>> mapofmaps = abcd(<String>, <Integer>);
I am trying to print the the outer hashmap using the following code
for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
String key = entry.getKey();
System.out.println(key);
HashMap<String, String> value = entry.getValue();
System.out.println(key + "\t" + value);
}
I would like to iterate through the inner map. What would be the entryset variable there (??? in the code).
for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
String key = entry.getKey();
System.out.println(key);
for(Entry<String, HashMap<String, String>> entry : ????.entrySet()){
HashMap<String, String> value = entry.getValue();
System.out.println(key + "\t" + value);
}}
Is my logic for printing the hashmaps correct? or is there a better way to do that?
It will be entry.getValue().entrySet()
so
for(Entry<String, String> innerEntry : entry.getValue().entrySet()){
then you can use
String key = innerEntry.getKey();
String value = innerEntry.getValue();
It is worth mentioning that, this can also be done Using java 8 Streams and lambda expressions
HashMap<String, HashMap<String, String>> mapofmaps = new HashMap<>();
HashMap<String,String> map1 = new HashMap<>();
map1.put("map1_key1", "map1_value1");
HashMap<String,String> map2 = new HashMap<>();
map2.put("map2_key1", "map2_value1");
mapofmaps.put("map1", map1);
mapofmaps.put("map2", map2);
// To print the keys and values
mapofmaps.forEach((K,V)->{ // mapofmaps entries
V.forEach((X,Y)->{ // inner Hashmap enteries
System.out.println(X+" "+Y); // print key and value of inner Hashmap
});
});
mapofmaps.forEach((K,V) : This expects a lambda expressions which takes two inputs i.e Key (String) and Value (HashMap)
V.forEach((X,Y)->{ : As this is applied on inner (V: fetched through previous foreach) hashmap so both Key and Value will be strings
Reference for further reading :
Lambda Expressions
Map foreach description
A Straight forward example with data
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Motorolla", 20);
map.put("RealMe", 30);
map.put("Oppo", 40);
map.put("Sony", 50);
map.put("OnePlus", 60);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ", Stock : " + entry.getValue());
}
Using lambda expression
map.forEach((K,V) -> System.out.println(K + ", Stock : " + V));
I'm trying to iterate List<Map<String, String>> in Java. However, I'm not able to iterate it properly. Can any one guide me?
Iterator it = list.iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
Thanks,
public static void main(String[] args) {
List<Map<String, String>> myListOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("Fname", "Ankur");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("Lname", "Singhal");
myListOfMaps.add(map1);
myListOfMaps.add(map2);
for (int i = 0 ; i < myListOfMaps.size() ; i++) {
Map<String, String> myMap = myListOfMaps.get(i);
System.out.println("Data For Map" + i);
for (Entry<String, String> entrySet : myMap.entrySet()) {
System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
}
}
}
output
Data For Map0
Key = Fname , Value = Ankur
Data For Map1
Key = Lname , Value = Singhal
Forget using the iterator directly, why not simply this:
List<Map<String,String>> l = new ArrayList<>();
...
// add map elements to list
...
for (Map<String,String> m:l) {
for (Map.Entry<String,String> e:m.entrySet()) {
String key = e.getKey();
String value = e.getValue();
// Do something with key/value
}
}
This is called an Enhanced for Loop. Internally it will handle it as a for loop traversing the iterator of any collection, or any other implementation of the Iterable Interface.
It was already used for traversing the Map Entries in one answer, so why not for the list of maps?
Of course, for nested collections, you also need to know how to nest your for-loops (how you put one for loop inside the other).
You iterate over a list with elements of type Map<String, String>. So casting to Map.Entry will give you a ClassCastException.
Try it like this
Iterator it = list.iterator();
while (it.hasNext()) {
Map<String, String> map = (Map<String, String>) it.next();
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
It would be easier for you, if you didn't use the raw types Iterator and Map.Entry. Use generics wherever possible. So the code would look like this:
Iterator<Map<String, String>> it = list.iterator();
while (it.hasNext()) {
Map<String, String> map = it.next(); //so here you don't need a potentially unsafe cast
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
list has no entySet() method!
Try this:
final Iterator<Map<String, String>> it = list.iterator();
while (it.hasNext())
{
Map<String, String> mapElement = it.next();
// do what you want with the mapElement
}
Of course, you will need another loop to iterate over the elements in the map.
I've got a TreeMap that stores a HashMap inside of it. I feel like I should be able to find this, but I just can't seem to find it on Google.
I've got a TreeMap with a HashMap stored inside of it, I iterate over it like so:
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
That will print out an output (example line):
I/System.outīš 32: {walks=32, pic=http://****/images/walkers/chase.png, name=Chase, dist=6096.8589024135445}
I'm wondering how to now grab pic, name, dist from this HashMap.
Edit: I'm not understanding where people missed the point. I put a HashMap into the TreeMap. Inside of the TreeMap is a HashMap. I guess I can show you what a HashMap is, but you guys know that already!
TreeMap dist_mp=new TreeMap();
Map<String, String> mp1 = new HashMap<String,String>();
mp1.put("dist", distanceInMiles + "");
mp1.put("name", obj.getString("first_name"));
mp1.put("pic", obj.getString("pic"));
mp1.put("walks", obj.getString("walks"));
dist_mp.put(distanceInMiles, mp1);
All you need is a cast to the TreeMap values to a Map again:
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
// Cast to a Map again
Map<String, String> mp = (Map<String, String>) me.getValue();
// get() works now
System.out.print("name = " + mp.get("name"));
System.out.print("pic = " + mp.get("pic"));
System.out.println("dist = " + mp.get("dist"));
}
Need to iterate twice, one for TreeMap and then for HashMap
public static void main(String[] args) {
TreeMap<String, Map<String, String>> dist_mp = new TreeMap<String, Map<String, String>>();
Map<String, String> mp1 = new HashMap<String, String>();
mp1.put("dist", "6096.8589024135445");
mp1.put("name", "Chase");
mp1.put("pic", "http://****/images/walkers/chase.png");
mp1.put("walks", "32");
dist_mp.put("32", mp1);
for (Map.Entry<String, Map<String, String>> entry : dist_mp.entrySet()) {
String key = entry.getKey();
System.out.println(key);
Map<String, String> myMap = entry.getValue();
for (Map.Entry<String, String> entry1 : myMap.entrySet()) {
System.out.println(entry1.getKey() + " => " + entry1.getValue());
}
}
}
output
32
walks => 32
name => Chase
pic => http://****/images/walkers/chase.png
dist => 6096.8589024135445
Your HashMap seems to be holding an object of some class, which is depicted here:
{walks=32, pic=http://****/images/walkers/chase.png, name=Chase, dist=6096.8589024135445}
Identify the class, and if getter methods are available for pic, name, dist, then use them.
I think you are just asking how to get the value associated with a key:
map.get("pic");
You want me.getValue().get("pic"), me.getValue().get("name") and me.getValue().get("dist").
This assumes that you're using generics, that your TreeMap is declared as a Map<Integer, HashMap<String, String>> and that your Map.Entry that you iterate with is declared as a Map.Entry<Integer, HashMap<String, String>>.
Also, you could iterate more easily with a for-each loop.
Map<Integer, HashMap<String, String>> theTreeMap = new TreeMap<>();
// Populate the map here.
for (Map.Entry<Integer, HashMap<String, String>> me : theTreeMap.entrySet()) {
System.out.println(me.getValue().get("pic"));
System.out.println(me.getValue().get("name"));
System.out.println(me.getValue().get("dist"));
}
I have a HashMap, which contains another HashMap. I want to iterate over the first HashMap and use the Key values from that. Then, as I iterate over the first HashMap I want to start an inner loop iterating over the second HashMap, getting all the values.
The problem I have so far is that I can't figure out how to get the keys from the Iterator.
HashMap<String, HashMap<Integer, String>> subitems = myHashMap.get("mainitem1");
Collection c = subitems.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
// Get key somehow? itr.getKey() ???
// contains the sub items
HashMap productitem = (HashMap)itr.next();
}
The data that i get from subitems is this:
{Item1{0=sub1, 1=sub2}, Item2{0=sub3, 1=sub4}}
Then, in the while loop productitem contains the 'sub items'. But i can't find out where i can get the key value 'Item1' and 'Item2' from.
How can i get those?
You can't get the key from values().iterator().
You need to use entrySet().iterator(). That will return Map.Entry<K,V> objects on which you can call getKey() and getValue().
for (Map.Entry<Integer,Key> entry : subitems.keySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
// do stuff
}
I'd also like to add that having deeply nested maps of lists of maps is usually a sign that you really want to write custom classes to hold your data. Especially when the maps have pre-defined keys to be used and interpretation of the values in the lists depends on the position within the list! I call this code smell "object denial".
You can't go from value to key in a map. (There may be several keys mapping to the same value!)
You can iterate over the map entries though using subitems.entrySet().iterator(), or you can iterate over the keys, and in each iteration retrieve the associated value through subitems.get(key).
You could do something like this (using iterators):
Set<Entry<String, HashMap<Integer, String>>> c = subitems.entrySet();
Iterator<Entry<String, HashMap<Integer, String>>> iterator = c.iterator();
while(iterator.hasNext())
{
Entry<String, HashMap<Integer, String>> entry = iterator.next();
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
Iterator<Entry<Integer, String>> innerIterator = innerMap.entrySet().iterator();
while (innerIterator.hasNext()) {
Entry<Integer, String> innerEntry = innerIterator.next();
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
or like this using foreach structure:
for (Entry<String, HashMap<Integer,String>> entry : subitems.entrySet())
{
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
for (Entry<Integer, String> innerEntry : innerMap.entrySet())
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
java Collections provide facility of EntrySet. This is a list of objects which contain individual keys and values as its properties. You can take a iterator out of this list.
You can get keys as follows.
Iterator i= subitems.entrySet().iterator();
while(i.hasNext()){
String key= i.next().getkey();
}
You can iterate over entries using entrySet().iterator() on the first HashMap or get the keys and iterate over them: Instead of subitems.values().iterator() use subitems.keys().iterator() and use the next key to get the inner hashmap.