java - Spliterator state after "consumed" in Stream -


i think i've run issue assumption made: if spliterator's item isn't consumed stream, spliterator still able advance it. seems not case.

here's code demonstrate:

import java.util.spliterator; import java.util.function.function; import java.util.stream.collectors; import java.util.stream.stream; import java.util.stream.streamsupport;  /**  * created dsmith on 7/21/15.  */ public class spliteratortest {     public static void main(string[] args) {         system.out.println("test 1");         test1();          system.out.println("test 2");         test2();     }      public static void test1() {         final spliterator<string> spliterator1 = stream.of("a", "b", "c", "d", "e", "f").spliterator();          streamsupport.stream(spliterator1, false).                 limit(3).                 collect(collectors.tolist());          system.out.println("spliterator1.estimatesize() = " + spliterator1.estimatesize());     }      public static void test2() {         final spliterator<string> spliterator1 = stream.of("a", "b", "c", "d", "e", "f").spliterator();         final spliterator<string> spliterator2 = stream.of("1", "2", "3", "4", "5", "6").spliterator();          stream.of(streamsupport.stream(spliterator1, false), streamsupport.stream(spliterator2, false)).                 flatmap(function.identity()).                 limit(3).                 collect(collectors.tolist());          system.out.println("spliterator1.estimatesize() = " + spliterator1.estimatesize());         system.out.println("spliterator2.estimatesize() = " + spliterator2.estimatesize());     } } 

this outputs:

test 1 spliterator1.estimatesize() = 3 test 2 spliterator1.estimatesize() = 0 spliterator2.estimatesize() = 6 

i understand spliterators can split... seems non-split, sequential access intuitively preserve non-consumed items.

in test2, seems spliterator1 consumed after stream. in test1, not consumed.

is there can desired behavior, or doing shouldn't doing?

this implementation detail, way flatmap works doesn't split content or iterate on 1 element @ time. gobbles in 1 go. if stream.concat(...) instead of flatmap, should see difference:

stream.concat(streamsupport.stream(spliterator1, false), streamsupport.stream(spliterator2, false)).         limit(3).         collect(collectors.tolist());  system.out.println("spliterator1.estimatesize() = " + spliterator1.estimatesize()); system.out.println("spliterator2.estimatesize() = " + spliterator2.estimatesize()); 

output:

spliterator1.estimatesize() = 3 spliterator2.estimatesize() = 6 

am doing shouldn't doing?

in short, yes. streams library makes no promises in state leave spliterator after partial traversal.


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -