Is there a Java equivalent to C#'s 'yield' keyword?

前端 未结 6 1107
自闭症患者
自闭症患者 2020-11-27 11:36

I know there is no direct equivalent in Java itself, but perhaps a third party?

It is really convenient. Currently I\'d like to implement an iterator that yields all

6条回答
  •  自闭症患者
    2020-11-27 12:26

    I just published another (MIT-licensed) solution here, which launches the producer in a separate thread, and sets up a bounded queue between the producer and the consumer, allowing for buffering, flow control, and parallel pipelining between producer and consumer (so that the consumer can be working on consuming the previous item while the producer is working on producing the next item).

    You can use this anonymous inner class form:

    Iterable iterable = new Producer(queueSize) {
        @Override
        public void producer() {
            produce(someT);
        }
    };
    

    for example:

    for (Integer item : new Producer(/* queueSize = */ 5) {
        @Override
        public void producer() {
            for (int i = 0; i < 20; i++) {
                System.out.println("Producing " + i);
                produce(i);
            }
            System.out.println("Producer exiting");
        }
    }) {
        System.out.println("  Consuming " + item);
        Thread.sleep(200);
    }
    

    Or you can use lambda notation to cut down on boilerplate:

    for (Integer item : new Producer(/* queueSize = */ 5, producer -> {
        for (int i = 0; i < 20; i++) {
            System.out.println("Producing " + i);
            producer.produce(i);
        }
        System.out.println("Producer exiting");
    })) {
        System.out.println("  Consuming " + item);
        Thread.sleep(200);
    }
    

提交回复
热议问题