首先我们有两个集合A,B,我们以其中一个集合A为基准
想获得B集合中的元素,相对于A集合来说,哪些元素不存在,哪些元素A没有
业务场景:以db1中的数据为准,更新db2中的数据,db1有的,db2没有的进行添加操作,db2有的,db1没有的进行删除操作
那么我们就需要知道,哪些元素是要添加的,哪些是要删除的
传统做法:通过标记实现
private static Map<String, List<String>> getContrast(List<String> newTypeList, List<String> oldTypeList){
Map<String,Integer> map = new HashMap<>();
Map<String,List<String>> resultMap = new HashMap<>();
//被删除的集合
List<String> deleteList = new ArrayList<>();
//添加的集合
List<String> addList = new ArrayList<>();
//遍历标记新的集合元素为1
for (String nItem : newTypeList) {
map.put(nItem,1);
}
//遍历标记相同的集合元素为2
for (String oItem : oldTypeList) {
Integer tag = map.get(oItem);
if (tag != null) {
map.put(oItem,2);
continue;
}
//标记 旧集合元素为3
map.put(oItem,3);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue().equals(1)) {
addList.add(entry.getKey());
resultMap.put("addList",addList);
}
if (entry.getValue().equals(3)) {
deleteList.add(entry.getKey());
resultMap.put("delList",deleteList);
}
}
return resultMap;
}
测试:
public static void main(String[] args) {
List<String> newList = new ArrayList<>();
newList.add("apple");
newList.add("banana");
newList.add("pina");
List<String> oldList = new ArrayList<>();
oldList.add("apple");
oldList.add("mikl");
Map<String, List<String>> contrast = getContrast(newList, oldList);
for (Map.Entry<String, List<String>> stringListEntry : contrast.entrySet()) {
System.out.println(stringListEntry.getKey() + "-" + stringListEntry.getValue());
}
}
测试结果:我们可以看到相对新的集合来说,老的集合没有“banana”和“pina”,而老的集合有的“milk”新的集合则没有,结果正确

JAVA8做法:通过流实现
public static void main(String[]args){
List<String> list1 = new ArrayList<String>();
list1.add("apple");
list1.add("banana");
list1.add("pina");
List<String> list2 = new ArrayList<String>();
list2.add("apple");
list2.add("mikl");
//交集
List<String> collect1 = list1.stream().filter(num -> list2.contains(num))
.collect(Collectors.toList());
System.out.println("交集: " + collect1);
// collect1.stream().forEach(System.out::println);
//差集 list1-list2
List<String> collect2 = list1.stream().filter(num -> !list2.contains(num))
.collect(Collectors.toList());
System.out.println("addList 即差集list1-list2: " + collect2);
// collect2.stream().forEach(System.out::println);
//差集list2-list1
List<String> collect3 = list2.stream().filter(num -> !list1.contains(num))
.collect(Collectors.toList());
System.out.println("delList 即差集list2-list1: " + collect3);
// collect3.stream().forEach(System.out::println);
//并集 不去重
list1.addAll(list2);
System.out.println("并集 不去重: " + list1);
// list1.stream().forEach(System.out::println);
//并集 去重
List<String> collect4 = list1.stream().distinct().collect(Collectors.toList());
System.out.println("并集 去重: " + collect4);
// collect4.stream().forEach(System.out::println);
}
结果:

效果是一样的,但是代码量少了很多

3627

被折叠的 条评论
为什么被折叠?



