Skip to content
Advertisement

Divide a list into fixed number of list in java

I am trying to figure out an efficient way to divide a list into a fixed number of list

Example 1

Input – [1,2,3,4,5,6,7,8]

Number of lists – 4

Output- [1,2], [3,4], [5,6],[7,8]

Example 2

Input – [1,2,3,4,5,6,7,8,9,10]

Number of lists – 4

Output- [1,2,3], [4,5,6], [7,8],[9,10]

Not necessarily the order of elements should be fixed

I tried few examples but most of them were based on dividing the elements in chunks but not in a fixed number list

I do have this solution but I am interested if there is a better way especially in java 8

JavaScript

Advertisement

Answer

Edit: Please refer to this solution below for partitioning in N times,

Java 8

JavaScript

Using Guava

JavaScript

Apache Commons Util

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement