基于Java中的元素属性将列表拆分为多个子列表 [英] Split a list into multiple sublist based on element properties in Java

查看:36
本文介绍了基于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆