根据 Java 中的元素属性将列表拆分为多个子列表

Split a list into multiple sublist based on element properties in Java

有没有办法将一个列表拆分为多个列表?。根据元素的特定条件将给定列表分成两个或多个列表。

final List<AnswerRow> answerRows= getAnswerRows(.........);
final AnswerCollection answerCollections = new AnswerCollection();
answerCollections.addAll(answerRows);

The AnswerRow has properties like rowId, collectionId

我想根据 collectionId 创建一个或多个 AnswerCollections

Is there a way to split a list to multiple list?

是的,你可以这样做:

answerRows.subList(startIndex, endIndex);

Given list into two or more list based on a particular condition of it elements.

您必须根据您的特定条件计算 startend 索引,然后您可以使用上述函数从 ArrayList 中生成子列表。

例如,如果您想将 1000 个 answerRows 的批次传递给特定函数,那么您可以这样做:

int i = 0;
for(; i < max && i < answerRows.size(); i++) {
    if((i+1) % 1000 == 0) {
        /* Prepare SubList & Call Function */
        someFunction(answerRows.subList(i, i+1000));
    }
}
/* Final Iteration */
someFunction(answerRows.subList(i, answerRows.size() - 1));

如果您只想按 collectionId 对元素进行分组,您可以尝试

List<AnswerCollection> collections = answerRows.stream()
    .collect(Collectors.groupingBy(x -> x.collectionId))
    .entrySet().stream()
    .map(e -> { AnswerCollection c = new AnswerCollection(); c.addAll(e.getValue()); return c; })
    .collect(Collectors.toList());

以上代码将根据 collectionId.

生成一个 AnswerCollection

使用 Java 6 和 Apache Commons Collections,以下代码使用 Java 8 个流产生与上述代码相同的结果:

ListValuedMap<Long, AnswerRow> groups = new ArrayListValuedHashMap<Long, AnswerRow>();
for (AnswerRow row : answerRows)
    groups.put(row.collectionId, row);
List<AnswerCollection> collections = new ArrayList<AnswerCollection>(groups.size());
for (Long collectionId : groups.keySet()) {
    AnswerCollection c = new AnswerCollection();
    c.addAll(groups.get(collectionId));
    collections.add(c);
}