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

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

final List answerRows= getAnswerRows(.........); final AnswerCollection answerCollections = new AnswerCollection(); answerCollections.addAll(answerRows); The AnswerRow has properties like rowId, collectionId 

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

如果你只想按collectionId对元素进行分组,你可以尝试类似的东西

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

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

是的,你可以这样做:

 answerRows.subList(startIndex, endIndex); 

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

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

例如,如果要将1000个answerRows批量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));