调用带有参数的迭代器函数 Java

huangapple go评论63阅读模式
英文:

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&lt;P&gt;
{
	private final List&lt;P&gt; pra = new ArrayList&lt;P&gt;();

    public Iterator&lt;P&gt; iterator() 
	{
        return pra.iterator();
    }
	
	public Iterator&lt;P&gt; iterator(S s)
	{
		return pra.stream().filter(x -&gt; 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(&quot;%s\n&quot;, 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&lt;P&gt; pra = new ArrayList&lt;P&gt;();
    
    public Iterable&lt;P&gt; filter(S s) {
        return () -&gt; (pra.stream().filter(x -&gt; x.s==s).iterator());
    }
}

With that, you can use for (P p : f.filter(s)) ...

huangapple
  • 本文由 发表于 2020年10月25日 07:38:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64519020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定