Search code examples
javadictionaryforeachcycle

Yet another "Can only iterate over an array or an instance of java.lang.Iterable" issue


I have this code that return a java.lang.iterable error. I know where i'm doing the error, but I don't know exactly how to fix it.

Here's the code:

public class ManagementServiceHandler implements ManagementService.Iface {
    private Map<Node, Integer> nodes;
    private int portCount = 1025;

    public ManagementServiceHandler() {
      nodes = new HashMap<Node, Integer>();
    }

    //register node
    public int RegisterNode(Node hostAndService) throws TException {
        portCount++;
        nodes.put(hostAndService, portCount);

        return portCount;            
    }

    //get service
    public Map<String, Integer> getProvidersForServices(String svcName, int port) throws TException {
        Map<String, Integer> result = new HashMap<>();

        for (Map.Entry<Node, Integer> pair : nodes.entrySet()) {
            for (String nodeService : pair.getKey().serviceName) {
                if (nodeService.equals(svcName)) {
                    result.put(pair.getKey().serviceName, pair.getValue());
                    break;
                }
            }
        }

        return result;
    }
}

The problem lies in the second method, at the second foreach cycle. I'm not sure what should I put in the right part of the cycle, after pair.getKey(). What I want to do is cycling all the entries<Node, Integer>" inside the Map nodes, then write each entry of serviceName into the other Map result.

I know that the right part of the foreach statement represents the collection of elements through which I want to cycle, but this doesn't help me much in this case, besides the fact i'm coding that wrong..

Any hint?


Solution

  • Apparently all you want is assignment to a local variable. Replace

    for (String nodeService : pair.getKey().serviceName)
    

    with

    String nodeService = pair.getKey().serviceName;