英文:
Call iterator function with argument Java
问题
我有以下类似的类:
public class F implements Iterable<P>
{
private final List<P> pra = new ArrayList<P>();
public Iterator<P> iterator()
{
return pra.iterator();
}
public Iterator<P> iterator(S s)
{
return pra.stream().filter(x -> x.s == s).iterator();
}
}
public class P
{
//一些代码
}
public enum S
{
//一些代码
}
我不知道如何在主函数中通过foreach循环调用迭代器函数。
我的意思是,当迭代器函数没有参数时,很简单:
F f = new F();
for(P x: f)
{
System.out.printf("%s\n", p.toString());
}
但是当迭代器函数有参数时,我该如何做到同样的效果呢?
英文:
I have classes like these below:
public class F implements Iterable<P>
{
private final List<P> pra = new ArrayList<P>();
public Iterator<P> iterator()
{
return pra.iterator();
}
public Iterator<P> iterator(S s)
{
return pra.stream().filter(x -> x.s == s).iterator();
}
}
public class P
{
//some code
}
public enum S
{
//some code
}
And i don't know how to call the iterator function in main by foreach loop.
I mean, when the iterator funcion doesn't have an argument, it is simple:
F f = new F();
for(P x: f)
{
System.out.printf("%s\n", p.toString());
}
but how can I do the same, when the iterator function get an argument?
答案1
得分: 1
你需要增强型for循环的东西不是Iterator
,而是Iterable
。
如果你想要使用参数调用F
中的方法,并在增强型for循环中获得可用的内容,那么你的方法需要返回一个Iterable
。
public class F {
private final List<P> pra = new ArrayList<P>();
public Iterable<P> filter(S s) {
return () -> (pra.stream().filter(x -> x.s==s).iterator());
}
}
有了这个,你可以使用 for (P p : f.filter(s)) ...
。
英文:
The thing that you need for an enhanced for-loop is not an Iterator
, but an Iterable
.
If you want to call a method in F
with an argument, and get something you can use in an enhanced for-loop, then you need your method to return an Iterable
.
public class F {
private final List<P> pra = new ArrayList<P>();
public Iterable<P> filter(S s) {
return () -> (pra.stream().filter(x -> x.s==s).iterator());
}
}
With that, you can use for (P p : f.filter(s)) ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论