user1733335
user1733335

Reputation: 21

for each loop for nested tree map

I have a nested treeMap and need to check each of the inner map if it has a certain key. For instance:

TreeMap<String,TreeMap<String,Integer>> map

for each loop {
//check if the inner map has the key in it
}

How would I format the for-each loop? Thanks!

Upvotes: 2

Views: 5417

Answers (4)

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32014

Alternatively, you could use Guava TreeBasedTable, there are many handy methods to handle your nested data structure.

TreeBasedTable<String, String, Integer> tb = TreeBasedTable.create();
tb.put("rowA", "colA", 1);
tb.put("rowB", "colB", 2);

tb.containsRow("rowA");
...

Upvotes: 0

Vikdor
Vikdor

Reputation: 24134

You can use the entrySet() of the Map to iterate through the entries in a map as follows:

for (Map.Entry<String, TreeMap<String, Integer>> entry : map.entrySet())
{
    if (entry.getValue().containsKey(key)) {
        return entry.getValue().get(key);
    }
}

Or you can use the values() collection of the Map to iterate through the entries:

for (TreeMap<String, Integer> value : map.values())
{
    if (value.containsKey(key)) {
        return value().get(key);
    }
}

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

You can iterate over two nested maps with two nested "foreach" loops, like this:

for (Map.Entry<String,TreeMap<String,Integer>> entry1 : map.entrySet()) {
    Map<String,Integer> innerMap = entry1.getValue();
    if (innerMap.containsKey("my-key")) {
        System.out.println("Map at key "+entry1.getKey()+" contains 'my-key'");
    }
}

Upvotes: 2

Yogendra Singh
Yogendra Singh

Reputation: 34397

Get the values from the outer map, iterate the elements inside each. In each element, which is a TreeMap<String,Integer>, use containsKey to check if the map element contains the desired key.

    TreeMap<String,TreeMap<String,Integer>> map = 
                                  new TreeMap<String, TreeMap<String,Integer>>();
    for(TreeMap<String,Integer> mapElement: map.values()) {
        //check if the inner map has the key in it
        if(mapElement.containsKey("searchKey")){
            System.out.println("Match key found in this map element");
        }
    }

Upvotes: 1

Related Questions