天涯尽头无女友
您可以在流交易中尝试。下面是示例代码:StreamEx.collapse(...)final long MAX_SIZE_THRESHOLD = 12; // only for test purpose.// create the sample file objects with random size for test.Collection<FileObject> files = new Random().longs(0, 1000).limit(50).mapToObj(n -> new FileObject(n % 15, n)) .collect(Collectors.toList());// here is the final solution you can tryfinal MutableLong remaining = MutableLong.of(MAX_SIZE_THRESHOLD);List<List<FileObject>> result = StreamEx.of(files).collapse((a, b) -> { if (b.sizeInBytes <= remaining.value() - a.sizeInBytes) { remaining.subtract(a.sizeInBytes); return true; } else { remaining.setValue(MAX_SIZE_THRESHOLD); return false; }}, Collectors.toList()).toList();result.forEach(System.out::println);以下是您问题的第2部分嵌套的解决方案:groupingBy// import static java.util.stream.Collectors.*Map<Integer, Map<Integer, Map<Integer, List<FileObject>>>> result2 = files.stream() .filter(f -> f.sizeInBytes < MAX_SIZE_THRESHOLD) .collect(groupingBy(f -> f.getYear(), groupingBy(f -> f.getMonth(), groupingBy(f -> f.getDay(), toList()))));result2.entrySet().forEach(System.out::println);最后,这是我用来测试的:FileObjectstatic class FileObject { public long sizeInBytes; public long modifiedDate; public FileObject(long sizeInBytes, long modifiedDate) { this.sizeInBytes = sizeInBytes; this.modifiedDate = modifiedDate; } public int getYear() { return (int) modifiedDate / 100; // only for test purpose } public int getMonth() { return (int) (modifiedDate % 100) / 10; // only for test purpose } public int getDay() { return (int) modifiedDate % 10; // only for test purpose } @Override public String toString() { return sizeInBytes + "-" + modifiedDate; }}根据评论更新:您将需要 .Collectors.collectAndThenFunction<List<FileObject>, List<List<FileObject>>> finisher = fileObjs -> { MutableLong remaining2 = MutableLong.of(MAX_SIZE_THRESHOLD); return StreamEx.of(fileObjs).collapse((a, b) -> { if (b.sizeInBytes <= remaining2.value() - a.sizeInBytes) { remaining2.subtract(a.sizeInBytes); return true; } else { remaining2.setValue(MAX_SIZE_THRESHOLD); return false; } }, toList()).toList();};Map<Integer, Map<Integer, Map<Integer, List<List<FileObject>>>>> result4 = files.stream() .collect(groupingBy(f -> f.getYear(), groupingBy(f -> f.getMonth(), groupingBy(f -> f.getDay(), collectingAndThen(toList(), finisher)))));结果类型应为 ,而不是 。Map<Integer, Map<Integer, Map<Integer, List<List<FileObject>>>>>Map<Integer, Map<Integer, Map<Integer, List<FileObject>>>>顺便说一句,如果你不想写函数(我不:-)),试试我的库:算盘-Util:finisherFunction<List<FileObject>, List<List<FileObject>>> finisher2 = fileObjs -> Seq.of(fileObjs) .split(MutableLong.of(0), (f, sizeSum) -> sizeSum.addAndGet(f.sizeInBytes) <= MAX_SIZE_THRESHOLD, sizeSum -> sizeSum.setValue(0));// import static com.landawn.abacus.util.stream.Collectors.MoreCollectors.*;StreamEx.of(files) .toMap(f -> f.getYear(), groupingBy(f -> f.getMonth(), groupingBy(f -> f.getDay(), collectingAndThen(toList(), finisher2))));