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

kap*_*das 3 java collections apache-commons

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

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

The AnswerRow has properties like rowId, collectionId
Run Code Online (Sandbox Code Playgroud)

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

hal*_*bit 8

如果您只想通过组合元素,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());
Run Code Online (Sandbox Code Playgroud)

上面的代码会产生一个AnswerCollectioncollectionId.


使用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);
}
Run Code Online (Sandbox Code Playgroud)