在处理复杂的数据时,List
一、基本合并方法:使用Java 8 Stream API
Java 8引入了Stream API,它提供了一种声明式的方式来处理数据集合。使用Stream API合并List
import java.util.*;
import java.util.stream.Collectors;
public class ListMapMergeExample {
public static void main(String[] args) {
List<Map<String, Object>> list1 = Arrays.asList(
new HashMap<>(Collections.singletonMap("id", 1)),
new HashMap<>(Collections.singletonMap("id", 2))
);
List<Map<String, Object>> list2 = Arrays.asList(
new HashMap<>(Collections.singletonMap("id", 3)),
new HashMap<>(Collections.singletonMap("id", 4))
);
List<Map<String, Object>> mergedList = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
mergedList.forEach(map -> System.out.println(map));
}
}
在这个例子中,我们使用了Stream.concat方法将两个Listcollect(Collectors.toList())将结果收集到一个新的List中。
二、基于键值对合并
当合并的List
import java.util.*;
import java.util.stream.Collectors;
public class ListMapMergeExample {
public static void main(String[] args) {
List<Map<String, Object>> list1 = Arrays.asList(
new HashMap<>(Collections.singletonMap("id", 1)),
new HashMap<>(Collections.singletonMap("id", 2))
);
List<Map<String, Object>> list2 = Arrays.asList(
new HashMap<>(Collections.singletonMap("id", 1, "value", "value1")),
new HashMap<>(Collections.singletonMap("id", 2, "value", "value2"))
);
List<Map<String, Object>> mergedList = list1.stream()
.collect(Collectors.toMap(
map -> map.get("id"),
map -> map,
(existing, replacement) -> {
existing.putAll(replacement);
return existing;
}
));
mergedList.forEach(map -> System.out.println(map));
}
}
在这个例子中,我们使用了Collectors.toMap来合并具有相同键的Map。如果两个Map有相同的键,我们通过合并它们的值来处理冲突。
三、处理嵌套Map
当Map中包含嵌套的Map时,合并过程可能会变得复杂。以下是一个处理嵌套Map的例子:
import java.util.*;
import java.util.stream.Collectors;
public class ListMapMergeExample {
public static void main(String[] args) {
List<Map<String, Object>> list1 = Arrays.asList(
new HashMap<>(Collections.singletonMap("id", 1)),
new HashMap<>(Collections.singletonMap("id", 2))
);
List<Map<String, Object>> list2 = Arrays.asList(
new HashMap<>(Collections.singletonMap("id", 1, "details", new HashMap<>(Collections.singletonMap("name", "value1")))),
new HashMap<>(Collections.singletonMap("id", 2, "details", new HashMap<>(Collections.singletonMap("name", "value2"))))
);
List<Map<String, Object>> mergedList = list1.stream()
.collect(Collectors.toMap(
map -> map.get("id"),
map -> map,
(existing, replacement) -> {
if (existing.containsKey("details") && replacement.containsKey("details")) {
Map<String, Object> details1 = (Map<String, Object>) existing.get("details");
Map<String, Object> details2 = (Map<String, Object>) replacement.get("details");
details1.putAll(details2);
}
return existing;
}
));
mergedList.forEach(map -> System.out.println(map));
}
}
在这个例子中,我们处理了嵌套的Map,确保在合并时正确处理嵌套结构。
四、总结
合并List