Partition list to sub lists in Java8

Viewed 67

I'm wondering if there is any nice a way using Java 8 to do something like this:

int amount = 1000;
int firstIndex = 0;
int lastIndex = firstIndex + amount;
List<int> projectIdsList;

while (lastIndex < projectIdsList.size()){
        doSomethingWhitSubList(projectIdsList.subList(firstIndex, lastIndex));
        firstIndex = lastIndex;
        lastIndex = firstIndex + amount;
}
doSomethingWhitSubList(projectIdsList.subList(firstIndex,  projectIdsList.size());
1 Answers

You can partition the list into sublist using IntStream, and I'm not really sure about your intention after partition, but you can collect the sublist's into a list using collect

List<List<Integer>> subLists = IntStream.range(0,integers.size())
            .filter(i->i%amount == 0)
            .mapToObj(i->integers.subList(i,i+amount > integers.size() ? integers.size() : i+amount))
            .collect(Collectors.toList());

Or you can also use forEach for any operations after partitioning

IntStream.range(0,integers.size())
            .filter(i->i%amount == 0)
            .mapToObj(i->integers.subList(i,i+amount > integers.size() ? integers.size() : i+amount))
            .forEach(this::doSomethingWhitSubList);
Related