如何在以下示例中使用lambda表达式和流?

时间:2017-05-06 16:26:10

标签: lambda java-8 java-stream sikuli

如何使用lambda表达式编写以下过程,如何使用流编写它?

Screen myScreen = new Screen();
Pattern myPattern = new Pattern("img.png");

Iterator<Match> it = myScreen.findAll(myPattern);
  while (it.hasNext())
    it.next().click();

4 个答案:

答案 0 :(得分:4)

或者,在Java 8中,Iterator接口具有默认方法forEachRemaining(Consumer)

那个人可以解决你的问题,而不必求助于溪流。你可以这样做:

Iterator<Match> it = myScreen.findAll(myPattern);
it.forEachRemaining(Match::click);

答案 1 :(得分:2)

您可以使用Apache Commons Collections utils来执行此操作。例如:

Iterator<Match> matches = s.findAll("someImage.png");
List<Match> list = IteratorUtils.toList(matches);
list.stream().forEach(Match::highlight);

答案 2 :(得分:2)

如果你真的想要使用带有lambdas的Stream,你必须首先将Iterator转换为Stream,然后你可以使用这个Stream迭代你的对象并使用方法调用它们的#include <semaphore.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <time.h> int numTickets; sem_t mySem; void* sell_ticket(void *sellerNum) { int sell = (int) sellerNum; int ticketsSold = 0; while (numTickets > 0) { srand ( time(NULL) ); int random_number = rand(); for (int i = 1; i < random_number % 5 ; i++) { if (numTickets > 0) { sem_wait(&mySem); numTickets--; ticketsSold++; printf("Seller # %d sold a ticket. Tickets left: %d\n", sell, numTickets); sem_post(&mySem); } } } printf("Seller #%d noticed all tickets sold! (I sold %d myself) \n", sell, ticketsSold); } int main() { numTickets = 50; int numSellers = 4; sem_init(&mySem, 0, 1); pthread_t sellerThread; for (int i = 0; i < numSellers; i++) { pthread_create(&sellerThread, NULL, sell_ticket, (void *)i); } for (int i = 0; i < numSellers; i++) { pthread_join(sellerThread, NULL); } printf("All tickets sold!\n"); return 0; } 方法参考:

click

或者如果你想使用一个显式的lambda表达式:

Iterator<Match> it = myScreen.findAll(myPattern);

// convert Iterator to Stream
Iterable<Match> iterable = () -> it;
Stream<Match> stream = StreamSupport.stream(iterable.spliterator(), false);

// invoke click on each object
stream.forEach(Match::click);

答案 3 :(得分:2)

那么一种迭代类似for循环或迭代器的流 - 通过Stream.iterate,但它将出现在jdk-9中。但是使用它并不是那么简单 - 因为它的行为与for循环完全相同,因此并不完全符合您的预期。例如:

 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]

或者这个:

 Iterator<Integer> iter = List.of(1).iterator();

    Stream.iterate(iter.next(), i -> iter.hasNext(), i -> iter.next())
            .forEach(System.out::println); // prints nothing

对于你需要forEachRemaining的情况,但它没有&#34;魔法&#34;,在内部它完全按照你的方式行事:

default void forEachRemaining(Consumer<? super E> action) {
    Objects.requireNonNull(action);
    while (hasNext())
        action.accept(next());
}