我有一个这样的对象列表:
[
{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 的新酷特性来实现这一点?