根据Java中的元素属性将列表拆分为多个子列表 [英] Split a list into multiple sublist based on element properties in Java
问题描述
是否可以将一个列表拆分为多个列表?根据it元素的特定条件将给定列表分为两个或多个列表.
Is there a way to split a list to multiple list?. Given list into two or more list based on a particular condition of it elements.
final List<AnswerRow> answerRows= getAnswerRows(.........);
final AnswerCollection answerCollections = new AnswerCollection();
answerCollections.addAll(answerRows);
The AnswerRow has properties like rowId, collectionId
基于collectionId我想创建一个或多个AnswerCollections
based on collectionId i want to create one or more AnswerCollections
推荐答案
如果您只想按collectionId
对元素进行分组,则可以尝试类似
If you just want to group elements by collectionId
you could try something like
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
.
Above code will produce one AnswerCollection
per collectionId
.
对于Java 6和Apache Commons Collections,以下代码使用Java 8流产生与上述代码相同的结果:
With Java 6 and Apache Commons Collections, the following code produce the same results as the above code using Java 8 streams:
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中的元素属性将列表拆分为多个子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!