英文:
How to group a object list into a map and select the first object of different type for each key using java stream?
问题
// 你的原始数据
List<Object1> list1;
// 将List<Object1>转换为Map<String, Object2>
Map<String, Object2> map1 = list1.stream()
.collect(Collectors.groupingBy(
Object1::getCity,
Collectors.collectingAndThen(
Collectors.minBy(Comparator.comparing(Object1::getUserDefinedMethod)),
optionalObject1 -> optionalObject1.map(obj1 ->
new Object2(obj1.getValue1(), obj1.getValue2(), obj1.getValue3())
).orElse(null)
)
));
请注意,上述代码的解释和结果已经在你提供的信息中进行了说明,因此我没有再次提供解释。如果你有任何问题或需要进一步的帮助,请随时提问。
英文:
I have data like: List<Object1> list1
.
I need to convert it to 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));
e.g.
[
{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}
}
答案1
得分: 1
你可以使用Collectors.toMap
,并定义合并函数以保留每个键的第一个值。
Map<String, Object2> map =
list1.stream()
.collect(Collectors.toMap(Object1::getCity,
p -> new Object2(p.getvalue1(), p.getvalue2(), p.getvalue3()),
(a, b) -> a));
英文:
You can use Collectors.toMap
and define the merge function to take first one for each key.
Map<String, Object2> map =
list1.stream()
.collect(Collectors.toMap(Object1::getCity,
p -> new Object2(p.getvalue1(),p.getvalue2(),p.getvalue3())
(a, b) -> a));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论