Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lambda expressions and streams in the following example?

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();
like image 925
hal Avatar asked Dec 03 '25 14:12

hal


2 Answers

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);
like image 137
Edwin Dalorzo Avatar answered Dec 07 '25 02:12

Edwin Dalorzo


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());
}
like image 40
Eugene Avatar answered Dec 07 '25 03:12

Eugene