英文:
Merge maps from a list of maps java8
问题
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Map<String, Object>> l1 = new ArrayList<>();
Map<String, Object> m1 = new HashMap<>();
m1.put("name", "alex");
m1.put("age", "40");
l1.add(m1);
m1 = new HashMap<>();
m1.put("name", "alex");
m1.put("state", "Texas");
l1.add(m1);
m1 = new HashMap<>();
m1.put("name", "alice");
m1.put("age", "35");
l1.add(m1);
m1 = new HashMap<>();
m1.put("name", "alice");
m1.put("state", "Arizona");
l1.add(m1);
m1 = new HashMap<>();
m1.put("name", "bob");
m1.put("age", "25");
l1.add(m1);
m1 = new HashMap<>();
m1.put("name", "bob");
m1.put("state", "Utah");
l1.add(m1);
List<Map<String, Object>> outputList = l1.stream()
.collect(Collectors.groupingBy(m -> m.get("name")))
.values()
.stream()
.map(group -> group.stream()
.reduce((m, acc) -> {
m.putAll(acc);
return m;
})
.orElse(new HashMap<>()))
.collect(Collectors.toList());
System.out.println(outputList);
}
}
注意:上面的代码是你提供的问题的Java代码部分。如果你还需要代码之外的解释或者有其他问题,请随时提问。
英文:
Hello fellow developers,
Need your expertise on below problem
I have a below incoming list of maps
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("name", "alex");
m1.put("age", "40");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alex");
m1.put("state", "Texas");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alice");
m1.put("age", "35");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alice");
m1.put("state", "Arizona");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "bob");
m1.put("age", "25");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "bob");
m1.put("state", "Utah");
l1.add(m1);
I want the output list of map as below using java 8 streams-
[{name="alex", age="40", state="Texas"}
{name="alice", age="35", state="Arizona"}
{name="bob", age="25", state="Utah"}]
Appreciate any help here.
答案1
得分: 2
你可以使用带有合并函数的toMap()
收集器。
l1.stream()
.collect(Collectors.toMap(m -> m.get("name").toString(), Function.identity(),
(map1, map2) -> { map1.putAll(map2); return map1;})
)
.values();
在这个解决方案中,我们根据“name”键的值合并了映射。因此,如果两个映射在“name”键上具有相同的值,它们将被合并。
由于toMap()
收集器的结果在这里是Map<String, Map<String, Object>>
,而期望的结果是Map<String, Object>
,所以我们调用了values()
方法。
英文:
You can use toMap()
collector with merge function.
l1.stream()
.collect(Collectors.toMap(m -> m.get("name").toString(), Function.identity(),
(map1, map2) -> { map1.putAll(map2); return map1;})
)
.values();
Indeed in this solution, we merge maps based on name key value. so if two maps have the same value for name key then they will merge.
since toMap() collector's result is Map<String,Map<String,Object>>
here and desire result is Map<String,Object>
so we have called values()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论