java - Collect results from parallel stream -
i have piece of code 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 way have create arraylist every hen, , eggs not collected until hen 100% processed. this:
list<egg> eggs = hens.parallelstream().map(hen -> { while (hen.hasegg()) { yield return hen.getegg(); } }).collect(collectors.tolist()); but java not have yield return. there way implement it?
your hen class poorly adapted stream api. provided cannot change , has no other useful methods (like collection<egg> getalleggs() or iterator<egg> eggiterator()), can create egg stream this:
public static stream<egg> eggs(hen hen) { iterator<egg> = 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); } now can use in following manner:
list<egg> eggs = hens.parallelstream() .flatmap(hen -> eggs(hen)) .collect(collectors.tolist()); of course better stream implementation might possible if can change hen class.
Comments
Post a Comment