将列表拆分为 java 中的列表列表

Split a list to list of lists in java

我有一个文件class

public class Document {
    // system
    private String documentId;
    private String documentTitle;
    private Date creationDate;
    private long fileSize;
    private String fileName;
    private String mimeType;
}

我有一种根据文件大小拆分列表的方法,我想要一个列表列表,其中每个列表都有一个最大文件大小为 1GB 的文档 例如:有 4 个文档,文件大小分别为 0.3GB、0.5GB、0.9GB、0.8GB 在我想要的列表列表中,第一个列表应包含 2 个文档,因为大小为 0.8GB,如果我们添加第 3 个,文件大小将超过 1 GB, 第二个列表应该包含一个 0.9 GB 的文件,第三个列表应该包含一个 0.8GB 的​​文件

public List<List<DocPakDocument>> groupDocuments(List<Document> document) {
    
        /* Group documents based on fileSize i.e. add document to a list, keeping the total fize size less than maxfileSize which is 1GB    */
        
        
        return null;        
    }

这是一种非常直接的方法。这里并不真正需要流式解决方案。

假设 List<Document> docs 有文件。

根据文件大小对文档列表进行排序

docs.sort(Comparator.comparing(Document::getFileSize));

当合并大小小于 1GB 时,继续将文档添加到当前列表。然后换一个新列表。

long max = 1_000_000_000;

List<List<Document>> lib = new ArrayList<>();
long currentSize = 0;

List<Document> temp =new ArrayList<>();
lib.add(temp);

for (Document d : docs) {
    currentSize += d.getFileSize();
    if (currentSize <= max) {
        temp.add(d);
        continue;
    }
    currentSize = d.getFileSize();
    lib.add(temp = new ArrayList<>());
    temp.add(d);
}

lib.stream().forEach(System.out::println);