1

If I have a class

public class Op {
    public Map<String, String> ops;
}

How can I make it executable in forEach loop?

for (String key : op) {
    System.out.println(op.ops.get(key))
}

UPD

Here is my solution

Op op = new Op(new HashMap<String, String>() {{
    put("a", "1");
    put("b", "2");
    put("c", "3");
}});

for (String key : op) System.out.println(op.map.get(key));

class Op implements Iterable<String> {    
    Map<String, String> map;
    public Op(Map<String, String> map) {
        this.map = map;
    }   
    public Iterator<String> iterator() {
        return map.keySet().iterator();
    }
}

But I'm not sure about verbosity. Is it too verbose? Maybe there is a much concise way to implement it?

barbara
  • 3,111
  • 6
  • 30
  • 58
  • 3
    http://tutorials.jenkov.com/java-generics/implementing-iterable.html – buxter Jan 08 '15 at 13:24
  • Yes. It's good example. But I don't need to write a separate Iterator class. I need a code as concise as possible, with minimal amount of lines of code. – barbara Jan 08 '15 at 13:35

3 Answers3

2

You are interested in looping over a SetEntry list.

for (Map.Entry<String, String > entry : ops.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    // ...
}

Propable duplicate of: Iterate through a HashMap

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57
0

In this exact case, use #entrySet, #keySet or #values as specified in the API docs.

In a general case, an object is iterable using the enhanced for loop, if it is implementing the interface Iterable. The most of the standard java collections are implementing this interface.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
0
public class Op implements Iterable<Map.Entry<String,String>> {
public Map<String, String> ops;

@Override
public Iterator<Map.Entry<String,String>> iterator() {
    return ops.entrySet().iterator();
}

}

Example:

for (Map.Entry<String, String> n : testOp){
        System.out.println("Key: " + n.getKey() + " Value: " + n.getValue());
    }
buxter
  • 583
  • 4
  • 14