[英]How to group a object list into a map and select the first object of different type for each key using java stream?
I have data like: List<Object1> list1
.我有这样的数据:
List<Object1> list1
。
I need to convert it to Map<String, Object2> map1
.我需要将其转换为
Map<String, Object2> map1
。
Code below下面的代码
map1=list1.stream()
.collect(Collectors
.groupingBy(Object1::getCity,Collectors
.mapping(p -> new Object2(p.getvalue1(),p.getvalue2(),p.getvalue3()),
here I want to get the first(based on any user defined method) item of Object1 type corresponding to each key));在这里我想得到第一个(基于任何用户定义的方法)对应于每个键的 Object1 类型的项目));
eg例如
[
{name:a,roll:2,id:3,age:24,city:goa},
{name:b,roll:3,id:3,age:24,city:Delhi},
{name:c,roll:2,id:1,age:27,city:goa}
]
Result:结果:
{
id=3:{name:a,city:goa},
id=1:{name:c,city:goa}
}
You can use Collectors.toMap
and define the merge function to take first one for each key.您可以使用
Collectors.toMap
并定义合并 function 以获取每个键的第一个。
Map<String, Object2> map =
list1.stream()
.collect(Collectors.toMap(Object1::getCity,
p -> new Object2(p.getvalue1(),p.getvalue2(),p.getvalue3())
(a, b) -> a));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.