跳过您的 Iterator/Iterable 混淆(并且 Iterable 基本上是一个 Iterator 工厂......所以您需要以任何方式编写一个 Iterator),我认为您的意思是这样的:
Iterator<Test> getTests(final Map<String,Test> testMap, final Set<String> strings) {
return new Iterator<Test>() {
private final Iterator<String> keyIter = strings.iterator();
private String lastKey;
public boolean hasNext() { return keyIter.hasNext(); }
public Test next() { lastKey = keyIter.next(); return testMap.get(lastKey); }
public void remove() { testMap.remove(lastKey); }
};
}
如果你想返回一个 Iterable,那么它必须是一个工厂:
Iterable<Test> getTests(final Map<String,Test> testMap, final Set<String> strings) {
return new Iterable<Test>() {
public Iterator<Test> iterator() {
return new Iterator<Test>() {
private final Iterator<String> keyIter = strings.iterator();
private String lastKey;
public boolean hasNext() { return keyIter.hasNext(); }
public Test next() { lastKey = keyIter.next(); return testMap.get(lastKey); }
public void remove() { testMap.remove(lastKey); }
};
}
};
}
为了获得额外的荣誉,您可以参数化此方法本身,并使用一种通用的方法来迭代地图中的选择:
Map<String, Action> map;
Set<String> keys;
for (Action x : filterMap(map, keys)) {
}