更新时间:2023-10-05 16:12:16
如果您只想按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);
}