2015-01-08 32 views
1

如果我有一個類如何在forEach循環中使類可執行?

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

我怎樣才能使它在執行forEach循環?

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

UPD

這裏是我的解決方案

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(); 
    } 
} 

但我不知道的詳細程度。它是否太冗長?也許有一個簡明的方法來實現它?

+3

http://tutorials.jenkov.com/java-generics/implementing-iterable.html – buxter

+0

是。這是一個很好的例子。但是我不需要編寫一個單獨的Iterator類。我需要儘可能簡潔的代碼,只需最少量的代碼。 – barbara

回答

2

您有興趣循環遍歷SetEntry列表。

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

的Propable重複:Iterate through a HashMap

0

在這種精確的情況下,使用#entrySet#keySet或如API docs指定#values

在一般情況下,如果對象正在實現接口Iterable,則使用增強for循環可迭代對象。大部分標準的java集合都在實現這個接口。

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(); 
} 

}

實施例:

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