title: Java 8 partition list
body: <p>Is it possible to partition a List in pure Jdk8 into equal chunks (sublists).</p>
  
  <p>I know it is possible using Guava <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html" rel="noreferrer">Lists</a> class, but can we do it with pure Jdk? I don't want to add new jars to my project, just for one use case.</p>
  
  <p><strong>SOLUTONS</strong>:</p>
  
  <p>The best solution till now was presented by <a href="https://stackoverflow.com/questions/32434592/partition-a-java-8-stream">tagir-valeev</a>:</p>
  
  <p>I have also found <a href="http://www.baeldung.com/java-list-split" rel="noreferrer">three other possibilities</a>, but they are ment for only few cases:</p>
  
  <p>1.Collectors.partitioningBy() to split the list into 2 sublists – as follows:</p>
  
  <pre><code>intList.stream().collect(Collectors.partitioningBy(s -&gt; s &gt; 6));
      List&lt;List&lt;Integer&gt;&gt; subSets = new ArrayList&lt;List&lt;Integer&gt;&gt;(groups.values());
  </code></pre>
  
  <p>2.Collectors.groupingBy() to split our list to multiple partitions:</p>
  
  <pre><code> Map&lt;Integer, List&lt;Integer&gt;&gt; groups = 
        intList.stream().collect(Collectors.groupingBy(s -&gt; (s - 1) / 3));
      List&lt;List&lt;Integer&gt;&gt; subSets = new ArrayList&lt;List&lt;Integer&gt;&gt;(groups.values());
  </code></pre>
  
  <p>3.Split by separator:</p>
  
  <pre><code>List&lt;Integer&gt; intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
  
      int[] indexes = 
        Stream.of(IntStream.of(-1), IntStream.range(0, intList.size())
        .filter(i -&gt; intList.get(i) == 0), IntStream.of(intList.size()))
        .flatMapToInt(s -&gt; s).toArray();
      List&lt;List&lt;Integer&gt;&gt; subSets = 
        IntStream.range(0, indexes.length - 1)
                 .mapToObj(i -&gt; intList.subList(indexes[i] + 1, indexes[i + 1]))
                 .collect(Collectors.toList());
  </code></pre>
  
  <p>4.Using Streams + counter <a href="https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/" rel="noreferrer">source</a>:</p>
  
  <pre><code>final List&lt;Integer&gt; numbers = Arrays.asList(1,2,3,4,5,6,7);
  final int chunkSize = 3;
  final AtomicInteger counter = new AtomicInteger();
  
  final Collection&lt;List&lt;Integer&gt;&gt; result = numbers.stream()
      .collect(Collectors.groupingBy(it -&gt; counter.getAndIncrement() / chunkSize))
      .values();
  </code></pre>