Skip to content
Advertisement

Convert for loop to stream

How to convert this block of code for loop into stream.

I am dividing my data list into partition on basis of partitionSize.. Also in last bit of code using sys out but will be calling a function inside..

I wanted to convert all for loop used in this part of code to streams

public static void main(String... args) {
    List<Long> a = Arrays.asList(11L, 12L, 13L, 9L, 10L, 11L, 23L, 14L, 38L, 49L, 50L, 68L, 79L, 87L);
    int partitionSize = 4;
    List<List<Long>> partitions = new ArrayList<>();

    for (int i = 0; i < a.size(); i += partitionSize)
        partitions.add(a.subList(i, Math.min(i + partitionSize, a.size())));

    for (List<Long> list : partitions)
        System.out.println(list);
}

Output:

[11, 12, 13, 9]
[10, 11, 23, 14]
[38, 49, 50, 68]
[79, 87]

Advertisement

Answer

public static void main(String... args) {
    int partitionSize = 4;
    List<Long> a = Arrays.asList(11L, 12L, 13L, 9L, 10L, 11L, 23L, 14L, 38L, 49L, 50L, 68L, 79L, 87L);

    List<List<Long>> partitions = IntStream.iterate(0, i -> i < a.size(), i -> i + partitionSize)
                                           .mapToObj(i -> a.subList(i, Math.min(a.size(), i + partitionSize)))
                                           .collect(Collectors.toList());

    partitions.forEach(System.out::println);
}

Output:

[11, 12, 13, 9]
[10, 11, 23, 14]
[38, 49, 50, 68]
[79, 87]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement