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

    
    
    List<Integer> intList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

    int listIteration=0;
    int numberOfSublist = 4;
    Map<Integer,List<Integer>> intmap = new HashMap<>();
    for (int mapIteration = 1; mapIteration < numberOfSublist +1; mapIteration++) {
        intmap.put(mapIteration, new ArrayList<Integer>());
    }
    while(listIteration<intList.size()) {
        for (int mapIteration = 1; mapIteration < numberOfSublist +1; mapIteration++) {
            if(listIteration==intList.size()) {
                break;
            }
            intmap.get(mapIteration).add(intList.get(listIteration++));
        }
    }
    

Advertisement

Answer

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

Java 8

class SamplePartition
{
    public static void main (String[] args) throws java.lang.Exception {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        final int N=4;
        System.out.println(part(l,N));
    }
        
        private static <T> List<List<T>> Part(List<T> objs, final int N) {
        return new ArrayList<>(IntStream.range(0, objs.size()).boxed().collect(
                Collectors.groupingBy(e->e%N,Collectors.mapping(e->objs.get(e), Collectors.toList())
                        )).values());
    }
}

Using Guava

`List<List<Integer>> partitionedLists = Lists.partition(intList, partition`);

Apache Commons Util

List<List<Integer>> partitionedLists = ListUtils.partition(largeList, partition);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement