0

I got the following error by trying to iterate through a HashMap by a key value:

Can only iterate over an array or an instance of java.lang.Iterable

I found some answers but those use .entrySet() and I need to iterate using a key value. This is my code so far:

for (ProtocolNode pendingNode : this.getPendingNodes().get(ExtractNumber(jid))){
  // Do stuff (ExractNumber is a String)
}

And the function:

public HashMap<String, ProtocolNode> getPendingNodes()
{
   return this.pending_nodes;
}

Thanks.

gi097
  • 7,313
  • 3
  • 27
  • 49
  • If you've got 1 key value only, then there is no need for iterating... Please elaborate and give more details on your issue. – dotvav Nov 30 '15 at 09:22
  • may i know what type are you using for ? – Vishal Gajera Nov 30 '15 at 09:22
  • Could you describe your problem a bit more? Do you want to loop over a single key or all keys? For the first one, if your value doesn´t represent something you can iterate over, then you´ll have the specific value you want yet, otherwise just use `this.getPendingNodes().entrySet()`. – SomeJavaGuy Nov 30 '15 at 09:22
  • @StefanBeike, it will return ProtocolNode – gi097 Nov 30 '15 at 09:23
  • @KevinEsche I want to iterate through the full HashMap and only return the matches as ProtocolNode pendingNode – gi097 Nov 30 '15 at 09:24
  • @JohnDoe if you want to iterate over a `Map` to get matches then you are in some way using the map the wrong way. Your key value should notify you about matches and you shouldn´t be in need to iterate over the map again. – SomeJavaGuy Nov 30 '15 at 09:27

2 Answers2

0

If you look at the method get in the javadoc.

https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

You will see that it returns a value, you can't iterate over a value. You are just accessing one item, the item associated with the 'jid'.

If you take a look at this answer: Iterate through a HashMap you can see how to iterate over a hashmap. And you will just need to use 'getPendingNodes()' to get the HashMap.

Community
  • 1
  • 1
Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
0

to iterate over a map you need to keep a Collection instance. Therefore change your map as below:

public HashMap<String, List<ProtocolNode>> getPendingNodes()
{
   return this.pending_nodes;
}

or to fix your own code use below method:

Map<String, ProtocolNode> testMap = new HashMap<String, ProtocolNode>();

        for( Entry<String, ProtocolNode> entry : testMap.entrySet() ){
            if( entry.getKey().equals( "MYKEY" ) ){
                System.out.println( entry.getValue() );
            }
        }

You have to use entryset, there's no other way.

Sercan Ozdemir
  • 4,641
  • 3
  • 34
  • 64