Manuel Wei&#223; - 1 year ago 63
Java Question

# Grouping an Integer List into Partitions

Is there a easy way to do following in a stream:

``````public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.print(partitioningValues(integerList, 3));
}

private static Map<Integer, List<Integer>> partitioningValues(List<Integer> integerList, int numberOfPartitions) {

Map<Integer, List<Integer>> integerListMap = new HashMap<>();
BigDecimal limit = BigDecimal.valueOf(integerList.size() / (double) numberOfPartitions);
int limitRounded = limit.setScale(0, BigDecimal.ROUND_UP).intValue();

for (int i = 0; i < numberOfPartitions; i++) {

int toIndex = ((i + 1) * limitRounded) > integerList.size() ? integerList.size() : (i + 1) * limitRounded;
integerListMap.put(i, integerList.subList(i * limitRounded, toIndex));
}

return integerListMap;
}
``````

Result:

{0=[1, 2, 3, 4], 1=[5, 6, 7, 8], 2=[9, 10]}

You can use `groupingBy` to split.

If the stream needs to be split by elements value

``````int split = 4;
Map<Integer, List<Integer>> map2 = integerList.stream().collect(Collectors.groupingBy(i -> --i / split));
System.out.println(map2);
``````

If the stream needs to be split by position

``````int[] pos = { -1 };
Map<Integer, List<Integer>> map = integerList.stream().peek(e -> pos[0]++).peek(System.out::println)
.collect(Collectors.groupingBy(e -> pos[0] / split));
System.out.println(map);
``````

output

``````{0=[1, 2, 3, 4], 1=[5, 6, 7, 8], 2=[9, 10]}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download