Reputation: 1759
I have a requirement to create a list of lists where the each list if of length 5 or the sum of the values in the list is <= 10 (whichever happens first). So far I have:
int currentSize = 0;
Boolean size = false;
Boolean length = false;
for (int s : keyListMax) {
if(currentSize >= 10) {
sizeReached = true;
}
if(currentList.size() >= 5) {
lengthReached = true;
}
if(!sizeReached && !lengthReached) {
currentSize += currentList.stream().mapToInt(Integer::intValue).sum();
currentList.add(s);
}
else {
result.add(0, currentList);
currentList.clear();
currentSize = 0;
}
}
System.out.println("Result is: " + result);
But the result is list of empty lists (maybe because of the clear() I’m using?). Also, how can I achieve this using Java 8?
Upvotes: 1
Views: 109
Reputation: 140494
A much easier solution is just to keep a running total of the elements you have added:
int i = 0;
while (i < keyListMax.size()) {
int start = i;
int sum = 0;
do {
sum += keyListMax.get(i);
++i;
} while (i < keyListMax.size()
&& i < start + 5
&& sum + keyListMax.get(i) <= 10);
result.add(0, new ArrayList<>(keyListMax.subList(start, i)));
}
Upvotes: 2