[英]How to groupby then toList the toMap using java8 stream
The original data is like: 原始数据如下:
[
{ 'k1': 'gbv1', 'k2': 'v2' },
{ 'k1': 'gbv1', 'k2': 'v4' },
]
The required data is like: 所需数据如下:
{
'gbv1': { 'v2': true, 'v4': true },
}
ie Group by k1
and then Select value of k2
. 即按k1
分组,然后选择k2
值。
What I currently have: 我目前拥有的:
examples.stream().collect(
Collectors.groupingBy(Example::getK1,
Collectors.mapping(Example::getK2,
Collectors.toList())));
It returns a list of value of k2
not a map; 它返回k2
的值列表而不是映射;
I'm most of the time with javascript and it's easy to do such kind of work because it's dynamic I think. 我大部分时间都使用javascript而且很容易做这样的工作,因为我认为这是动态的。
Use toMap
instead of mapping
: 使用toMap
而不是mapping
:
Map<String,Map<String,Boolean>> map =
examples.stream()
.collect(Collectors.groupingBy(Example::getK1,
Collectors.toMap(Example::getK2,v->true,(v1,v2)->v1)));
This is assuming both getK1()
and getK2()
return a String
. 这假设getK1()
和getK2()
返回一个String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.