1

How do I search for a Hashmap that contains String as a key and list of objects as value?

HashMap<String,List<PageObjectBaseClass>> ObjList1;

When I used

for (HashMap<String,List<PageObjectBaseClass>> map : ObjList1)

Am getting the error "Can only iterate over an array or an instance of java.lang.Iterable"

ItsMeGokul
  • 403
  • 1
  • 5
  • 16
  • 2
    Are you trying to iterate over the elements in ObjList1 or get a specific List out of ObjList1? – twinklehawk Jan 16 '18 at 21:46
  • 1
    *FYI:* Java naming convention is for variables to start with lowercase letter, so variable should be named `objList1`. – Andreas Jan 16 '18 at 21:49

4 Answers4

3

You'll need to enumerate over the entrySet like this:

for (Map.Entry<String, List<PageObjectBaseClass>> map : ObjList1.entrySet()){
    ....
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

You can only use the extended for-loop over objects that implement the Iterable interface. Map does not.

However it provides some utility method to access collections of its entries, keys and values which are of type Iterable. Therefore consider the following examples:

HashMap<A, B> map = new HashMap<>();

// Entries
for (Map.Entry<A, B> entry : map.entrySet​()) { ... }

// Keys
for (A key : map.keySet()) { ... }

// Values
for (B value : map.values()) { ... }

Here are links to the documentation of all three methods:

Note that all three accesses are fast, O(1). As you get collections that are internally used by the map. That is also why they are backed by the map, which means if you change something on the collections or the entries, the changes will be reflected inside the map too.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
1

There are many ways. The one I find most idiomatic and expressive is Map.forEach:

yourMap.forEach((key, value) -> {
    // key is of type String
    // value is List<PageObjectBaseClass>
});
fps
  • 33,623
  • 8
  • 55
  • 110
0

This an example from here

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}
Chris Sum
  • 123
  • 1
  • 2
  • 11
  • This answer is very inferior to answer using `foreach`. First it uses `while` that unless you are on ancient Java, is not recommended any more. Second it uses raw type and cast which again is bad. Third it does `remove` entry from `Map` that OP did not ask for. And finally there is no reason to copy answer from another question. You can simply mark the question as duplicate. – tsolakp Jan 16 '18 at 22:19