How do I write following procedure using lambda expressions, and how do I write it using streams?
Screen myScreen = new Screen();
Pattern myPattern = new Pattern("img.png");
Iterator<Match> it = myScreen.findAll(myPattern);
while (it.hasNext())
it.next().click();
Alternatively, in Java 8, the Iterator interface has a default method forEachRemaining(Consumer).
That one would solve your problem without having to resort to streams. You can simply do:
Iterator<Match> it = myScreen.findAll(myPattern);
it.forEachRemaining(Match::click);
Well there will be a way to iterate with streams like a for loop or an iterator - via Stream.iterate, but it will be present in jdk-9. But it is not that trivial to use - because it acts exactly like a for loop and thus not exactly what you might expect. For example:
Iterator<Integer> iter = List.of(1, 2, 3, 4).iterator();
Stream<Integer> stream = Stream.iterate(iter.next(),
i -> iter.hasNext(),
i -> iter.next());
stream.forEach(System.out::println); // prints [1,2,3]
Or this:
Iterator<Integer> iter = List.of(1).iterator();
Stream.iterate(iter.next(), i -> iter.hasNext(), i -> iter.next())
.forEach(System.out::println); // prints nothing
For the case that you need there's the forEachRemaining, but it's no "magic", internally it does exactly what you do:
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With