两个list比较其中的对象,返回新增删除修改内容

最近新的需求,涉及一个产品新老版本的数据进行比较,需要展示出新增,删除,修改的数据。 举个例子:原本a班级有小明:1号,5岁;小红:2号,6岁.。 现在a班新来了插班生小绿:3号,7岁,小明被劝退了,小红的年龄登记错了,改成7岁。 那老版本班级:1号-小明,2号-小红 新版本班级:2号-小红,3号-小绿 那新版本相较于老版本的变更为:

新增-3号,小绿
删除-1号,小明
修改-2号,小红

思路如下 1.把list转换成oldMap,newMap分别为新老版本的学生数据,key存放的是学号,value存放的是对象。 2.新建List,存放新老版本的学号,此时list内数据为[1,2,2,3],新增及修改的学号1,3只出现一次。 3.将List转换成一个countMap,key存放的是学号,value存放的是出现的次数 4.遍历countMap,如果value等于1(那就是新增或者删除)根据key,去oldMap和newMap中查询学生数据,如果在oldMap存在那就是删除了,如果newMap存在那就是新增了。如果value等于2,再去判断年龄是否修改,如果修改了那就是修改。

上代码

private void judgmentHospital(newList, oldList, arrayList){
          
   
		/*新老学生list->map*/
        Map<Long, Student> newCodeMap = newList.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
        Map<Long, Student> oldCodeMap = oldList.stream().collect(Collectors.toMap(Student::getId, Function.identity()));

        List<Long> codeString = Lists.newArrayList();
        codeString.addAll(newCodeMap.keySet());
        codeString.addAll(oldCodeMap.keySet());

        Map<Long, Long> counts =
                codeString.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));

        counts.forEach((code, count) -> {
          
   
            Student newItem = newCodeMap.get(code);
            Student oldItem = oldCodeMap.get(code);
            if (count == 1) {
          
   
                /*新版本新增的*/
                if (newItem != null) {
          
   
                    arrayList.add("新增学生"+newItem.getId()+newItem.getName());
                }
                /*新版本删除的*/
                if (oldItem != null) {
          
   
                    arrayList.add("删除学生"+newItem.getId()+newItem.getName());
                }
            } else {
          
   
                if (!newItem.equals(oldItem)) {
          
   
                    arrayList.add("修改学生"+newItem.getId()+newItem.getName());
                }
            }
        });
    }
经验分享 程序员 微信小程序 职场和发展