How to group a object list into a map and select the first object of different type for each key using java stream?

huangapple go评论78阅读模式
英文:

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&lt;Object1&gt; list1.

I need to convert it to Map&lt;String, Object2&gt; map1.

Code below

map1=list1.stream()    
.collect(Collectors  
.groupingBy(Object1::getCity,Collectors  
.mapping(p -&gt; 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&lt;String, Object2&gt; map = 
     list1.stream()
          .collect(Collectors.toMap(Object1::getCity,
                          p -&gt; new Object2(p.getvalue1(),p.getvalue2(),p.getvalue3())
                          (a, b) -&gt; a));

huangapple
  • 本文由 发表于 2020年10月7日 22:39:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64246453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定