Why lambda inside map is not running?

前端 未结 1 360
[愿得一人]
[愿得一人] 2021-01-14 11:47

I am trying to learn concurrency and lambdas in java 8. But my code is not entering lambda block inside map.

List bookList = new ArrayList

        
相关标签:
1条回答
  • 2021-01-14 12:25

    A stream pipeline is lazy. Without a terminal operation, your stream pipeline is not even executed. Stream.map is an intermediate operation so it won't trigger pipeline execution.

    Now you could add a forEach step with the lambda expression cf -> cf.join() for joining on your created CompletableFuture instances for your pipeline to be executed and wait for each of your async futures to complete. But doing this way will defeat the whole purpose of using asynchronous futures, because you're submitting them sequentially and waiting on the completion of each one before submitting the next one.

    Better yet, you could convert your stream to a parallel stream, use map with your async lambda body directly by removing the CompletableFuture.supplyAsync part and collecting with collect for a similar effect without the extra clutter.

    List<Book> bookList = isbnList.parallelStream()
        .map(isbn -> {
            try {
                List<String> pageContents = getUrlContents(webLink + isbn);
                return new Book(
                    parseBookTitle(pageContents),
                    isbn,
                    parseRank(pageContents)
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }).collect(Collectors.toList());
    

    Further reading: Stream operations and pipelines in the stream API javadoc.

    0 讨论(0)
提交回复
热议问题