我有字段Map<MyObject, String> myField
。我用它如下:
myField.forEach((myObject, text) -> myMethod(myObject, text));
我希望将此字段包装到新对象:
class MyFieldWrapper {
Map<MyObject, String> myField;
...
//methods do somethings with myField
...
}
如何在MyFieldWrapper中实现Iterable:myFieldWrapper.forEach((myObject, text) -> myMethod(myObject, text));
?
答案 0 :(得分:3)
正如@JBNizet所说,Map不是Iterable,但如果你想拥有forEach方法,这里有一个简单的实现:
class MyFieldWrapper {
Map<MyObject, String> myField;
....
public void forEach(BiConsumer<? super MyObject, ? super String> action){
myField.forEach(action);
}
}
已编辑:我使用BiConsumer
模板参数时出错。