简体   繁体   中英

Java: How to add lists to a list based on length or sum of values?

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?

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;
  while (i < keyListMax.size()
      && i < start + 5
      && (start == i  // Necessary in case keyListMax contains an element > 10.
          || sum + keyListMax.get(i) <= 10) {
    sum += keyListMax.get(i);
    ++i;
  }
  result.add(0, new ArrayList<>(keyListMax.subList(start, i)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM