In this Q&A, we'll go over how to split and iterate over the sub-collection using Spliterator
Java 8 Collection classes provide a method -spliterator()- to create a Spliterator. Spliterator.trySplit() will split the collection. One can iterate over the sub-collection using tryAdvance() or forEachRemaining() methods
See demo code below
List<String> ll = Arrays.asList("1a", "2a", "3a", "4a", "5a", "6a" );
Spliterator<String> s = ll.spliterator();
assertEquals("spliterator size match", 6, s.getExactSizeIfKnown());
Spliterator<String> s2 = s.trySplit();
assertEquals("spliterator size match", 3, s.getExactSizeIfKnown());
assertEquals("spliterator size match", 3, s2.getExactSizeIfKnown());
s.forEachRemaining(item->System.out.println(item));
s2.forEachRemaining(item->System.out.println(item));
Comments
Post a Comment