Collects the results of the parallel stream

I have a piece of code like this:

List eggs = hens.parallelStream().map(hen -> {
    ArrayList eggs = new ArrayList();
    while (hen.hasEgg()) {
        eggs.add(hen.getEgg());
    }
    return eggs;
}).flatMap(Collection::stream).collect(Collectors.toList());

But in this way I have to create an ArrayList for every hen, and eggs are not collected until a hen is 100% processed. I would like something like this:

List eggs = hens.parallelStream().map(hen -> {
    while (hen.hasEgg()) {
        yield return hen.getEgg();
    }
}).collect(Collectors.toList());

But Java does not have yield return. Is there a way to implement it?

Your Hen
class is poorly adapted to the Stream API. Provided that you cannot change it and it has no other useful methods (like Collection getAllEggs()
or Iterator eggIterator()
), you can create an egg stream like this:

public static Stream eggs(Hen hen) {
    Iterator it = new Iterator() {
        @Override
        public boolean hasNext() {
            return hen.hasEgg();
        }

        @Override
        public Egg next() {
            return hen.getEgg();
        }
    };
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), false);
}

Now you can use it in the following manner:

List eggs = hens.parallelStream()
                     .flatMap(hen -> eggs(hen))
                     .collect(Collectors.toList());

Of course better Stream
implementation might be possible if you can change the Hen
class.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Collects the results of the parallel stream

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录