List<List<String>> (@NotNull List<String> arguments, int groupSize) { assert arguments.size() % groupSize == 0 : "Arguments size should be divisible by group size"; ArrayList<List<String>> rc = new ArrayList<>(); int start = 0; int size = 0; int i = 0; for (; i < arguments.size(); i += groupSize) { int length = 0; for (int j = 0; j < groupSize; j++) { length += arguments.get(i + j).length(); } if (size + length > FILE_PATH_LIMIT) { if (start == i) { // to avoid empty chunks rc.add(arguments.subList(i, i + groupSize)); start = i + groupSize; size = 0; } else { rc.add(arguments.subList(start, i)); start = i; size = length; } } else { size += length; } } if (start != arguments.size()) { rc.add(arguments.subList(start, i)); } return rc; }