0

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?

3
  • Ok, I corrected it. But how can I call the iterator function which get an argument by foreach loop? Commented Oct 24, 2020 at 23:47
  • You can call it the same way as you did previously, this time adding an argument only. Commented Oct 24, 2020 at 23:49
  • try adding only the arguments and call. Commented Oct 25, 2020 at 8:33

1 Answer 1

1

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)) ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.