Java – collect results from parallel streams

I have a code like this:

List<Egg> eggs = hens.parallelStream().map(hen -> {
    ArrayList<Egg> 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 each hen and will not collect eggs until the hen is 100% processed I want something like this:

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

But Java has no yield Is there any way to achieve it?

Solution

Your hen class is hard to adapt to the stream API If you cannot change it and there are no other useful methods (such as collection < egg > getalleggs() or iterator < egg > eggiterator()), you can create the following egg stream:

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

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

You can now use it in the following ways:

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

Of course, if you can change the hen class, you can achieve a better stream implementation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>