Wednesday 15 September 2010

java - Skip last x elements in Stream -



java - Skip last x elements in Stream<T> -

if have stream<t>, can utilize skip(long) skip first few elements of stream. however, there seems no equivalent skipping given number of elements @ end of stream.

the obvious solution utilize limit(originallength - elementstoremoveatend), requires knowing initial length beforehand, isn't case.

is there way remove lastly few elements of stream of unknown length without having collect collection, count elements , stream again?

there no general storage-free solution streams may have unknown length. however, don’t need collect entire stream, need storage big number of elements want skip:

static <t> stream<t> skiplastelements(stream<t> s, int count) { if(count<=0) { if(count==0) homecoming s; throw new illegalargumentexception(count+" < 0"); } arraydeque<t> pending=new arraydeque<t>(count+1); spliterator<t> src=s.spliterator(); homecoming streamsupport.stream(new spliterator<t>() { public boolean tryadvance(consumer<? super t> action) { while(pending.size()<=count && src.tryadvance(pending::add)); if(pending.size()>count) { action.accept(pending.remove()); homecoming true; } homecoming false; } public spliterator<t> trysplit() { homecoming null; } public long estimatesize() { homecoming src.estimatesize()-count; } public int characteristics() { homecoming src.characteristics(); } }, false); } public static void main(string[] args) { skiplastelements(stream.of("foo", "bar", "baz", "hello", "world"), 2) .foreach(system.out::println); }

java java-8 java-stream

No comments:

Post a Comment