【发布时间】:2015-03-12 14:19:16
【问题描述】:
我有一个这样的对象列表:
[
{value: 1, tag: a},
{value: 2, tag: a},
{value: 3, tag: b},
{value: 4, tag: b},
{value: 5, tag: c},
]
其中每个对象都是Entry 类的实例,该类具有tag 和value 作为属性。我想以这种方式对它们进行分组:
{
a: [1, 2],
b: [3, 4],
c: [5],
}
这是我到目前为止所做的:
List<Entry> entries = <read from a file>
Map<String, List<Entry>> map = entries.stream()
.collect(Collectors.groupingBy(Entry::getTag, LinkedHashMap::new, toList()));
这是我的结果(不是我想要的):
{
a: [{value: 1, tag: a}, {value: 2, tag: a}],
b: [{value: 3, tag: b}, {value: 4, tag: b}],
c: [{value: 5, tag: c}],
}
换句话说,我想要一个字符串列表作为我的新映射 (Map<String, List<String>>) 的值,而不是对象列表 (Map<String, List<Entry>>)。
如何使用 Java 8 的新酷特性实现这一点?
【问题讨论】:
标签: java java-8 java-stream collectors