【问题标题】:Split a list into multiple sublist based on element properties in Java基于Java中的元素属性将列表拆分为多个子列表
【发布时间】:2016-06-02 00:15:57
【问题描述】:

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

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

The AnswerRow has properties like rowId, collectionId

基于 collectionId 我想创建一个或多个 AnswerCollections

【问题讨论】:

  • 是的。你怀疑这是可能的吗?您对这样做有什么具体问题?
  • 可以根据list元素属性拆分成多个list吗?

标签: java collections apache-commons


【解决方案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);
}

【讨论】:

  • 与 Java 1.6 有什么关系吗?
  • @kapildas 我用 Apache Commons Collections 的 Java 6 代码扩展了我的答案。
【解决方案2】:

有没有办法将一个列表拆分为多个列表?

是的,你可以这样做:

answerRows.subList(startIndex, endIndex);

根据特定条件将给定列表分成两个或多个列表 元素。

您必须根据您的具体情况计算 startend 索引,然后您可以使用上述函数从 ArrayList 中生成 subList。

例如,如果您想将 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多