java集合获取两个集合的交集差集

import com.google.gson.Gson;
import org.apache.commons.lang.ObjectUtils;
import java.io.*;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.collections.CollectionUtils;

public class Test {
    static class User implements Serializable {
        private String id;
        private String name;
        private String age;
        private String sex;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public User(String id, String name, String age, String sex) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.sex = sex;
        }

        @Override
        public int hashCode() {
            String codestr=this.id.hashCode() + this.name.hashCode() +this.age.hashCode()+this.sex.hashCode()+"";
            return codestr.hashCode();
        }
    }
    public static List<User> getData(int size){
        List<User> result=new ArrayList<>();
        for (int i = 1; i < size; i++) {
            result.add(new User(i+"","cs"+i+size,i+10+"",i%2+""));
        }
        result.add(new User(size+1+"","cs",10+"",size%2+""));
        result.add(new User(size+2+"","cs",12+"",size+1%2+""));
        return result;
    }
    public static void main(String[] args) {
        List<User> dbData = getData(11);
        List<User> newData = getData(6);

        List<User> addData = new CopyOnWriteArrayList<User>();
        List<User> deleteData = new CopyOnWriteArrayList<User>();
        List<User> updatedData = new CopyOnWriteArrayList<User>();
        XObjectUtils.compareCopyId(dbData, newData, addData, updatedData,
                deleteData, new Comparator<User>() {
                    @Override
                    public int compare(User u1, User u2) {
                        if(u1==null||u2==null)
                            return -1;
                        return u1.getId().hashCode() - u2.getId().hashCode();
                    }
                });

        Gson gson=new Gson();

        if (CollectionUtils.isNotEmpty(addData))
            System.out.println("add:\t\n"+gson.toJson(addData));

        if (CollectionUtils.isNotEmpty(deleteData)) {
            System.out.println("del:\t\n"+gson.toJson(deleteData));
        }

        if (CollectionUtils.isNotEmpty(updatedData))
            System.out.println("set:\t\n"+gson.toJson(updatedData));
    }


    static class XObjectUtils {

        public static Map<String, List<Object>> getDifferentProperities(Object thisObject, Object anotherObject) {
            if (thisObject == null || anotherObject == null)
                throw new NullPointerException();

            if (thisObject.getClass() != anotherObject.getClass())
                throw new IllegalArgumentException("the two objects are not the same class type");

            Map<String, List<Object>> differentProperities = new HashMap<String, List<Object>>();

            Class<?> clazz = thisObject.getClass();

            while (clazz != null) {
                Field[] fields = clazz.getDeclaredFields();

                try {
                    AccessibleObject.setAccessible(fields, true);

                    for (Field field : fields) {
                        Object obj1 = field.get(thisObject);
                        Object obj2 = field.get(anotherObject);
                        if (!ObjectUtils.equals(obj1, obj2)) {
                            List<Object> list = new ArrayList<Object>();
                            list.add(obj1);
                            list.add(obj2);
                            differentProperities.put(field.getName(), list);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                clazz = clazz.getSuperclass();
            }

            return differentProperities;

        }

        public static <T> void copyProperities(T dest, T src) {
            if (dest == null || src == null)
                throw new NullPointerException();

            if (dest.getClass() != src.getClass())
                throw new IllegalArgumentException("dest and src are not the same class type");

            Class<?> clazz = dest.getClass();

            while (clazz != Object.class) {
                Field[] fields = clazz.getDeclaredFields();
                try {
                    AccessibleObject.setAccessible(fields, true);

                    for (Field field : fields) {
                        Object obj1 = field.get(dest);
                        Object obj2 = field.get(src);
                        if (!org.apache.commons.lang.ObjectUtils.equals(obj1, obj2))
                            field.set(dest, obj2);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                clazz = clazz.getSuperclass();
            }
        }
        public static <T> void copyProperities2(T dest, T src) {
            if (dest == null || src == null)
                throw new NullPointerException();

            Class<?> clazz = src.getClass();

            while (clazz != Object.class) {
                Field[] fields = clazz.getDeclaredFields();
                try {
                    AccessibleObject.setAccessible(fields, true);
                    Field destField;
                    for (Field srcField : fields) {
                        if(java.lang.reflect.Modifier.isFinal(srcField.getModifiers()))
                            continue;
                        Object obj1 = srcField.get(src);
                        try {
                            destField=dest.getClass().getDeclaredField(srcField.getName());
                            if(destField==null)
                                continue;
                        }catch(Exception ex) {
                            continue;
                        }
                        destField.setAccessible(true);
                        Object obj2 = destField.get(dest);
                        if (!org.apache.commons.lang.ObjectUtils.equals(obj1, obj2))
                            destField.set(dest, obj1);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                clazz = clazz.getSuperclass();
            }
        }

        public static <T> List<T> newArrayList(T... objs) {
            List<T> results = new ArrayList<T>();
            for (T obj : objs) {
                results.add(obj);
            }
            return results;
        }

        public static String toString(Object[] objects) {
            StringBuilder sb = new StringBuilder();
            int index = 0;
            if (objects == null)
                return "";
            for (Object obj : objects) {
                sb.append(obj);
                if (index != objects.length - 1)
                    sb.append(",");
                index++;
            }
            return sb.toString();
        }

        public static <T> void compare(List<T> oldBos, List<T> newBos, List<T> addedBos, List<T> updatedBos,
                                       List<T> deletedBos, Comparator<T> comparator) {
            List<T> copyOldBos = new CopyOnWriteArrayList<T>(oldBos);
            for (T newBo : newBos) {
                boolean flag = false;
                for (T oldBo : copyOldBos) {
                    if (comparator.compare(newBo, oldBo) == 0) {
                        boolean isDifferent = isDifferent(oldBo, newBo);
                        if (isDifferent) {
                            copyProperities(oldBo, newBo);
                            updatedBos.add(oldBo);
                        }
                        flag = true;
                        copyOldBos.remove(oldBo);
                        break;
                    }
                }
                if (!flag) {
                    addedBos.add(newBo);
                }
                flag = false;
            }
            deletedBos.addAll(copyOldBos);
        }

        public static <T> void compareCopyId(List<T> oldBos, List<T> newBos, List<T> addedBos, List<T> updatedBos,
                                             List<T> deletedBos, Comparator<T> comparator) {
            List<T> copyOldBos = new CopyOnWriteArrayList<T>(oldBos);
            for (T newBo : newBos) {
                boolean flag = false;
                for (T oldBo : copyOldBos) {
                    if (comparator.compare(newBo, oldBo) == 0) {
                        boolean isDifferent = isDifferentNoId(oldBo, newBo);
                        if (isDifferent) {
                            copyProperities(oldBo, newBo);
                            updatedBos.add(oldBo);
                        }
                        flag = true;
                        copyOldBos.remove(oldBo);
                        break;
                    }
                }
                if (!flag) {
                    addedBos.add(newBo);
                }
                flag = false;
            }
            deletedBos.addAll(copyOldBos);
        }

        public static boolean isDifferentNoId(Object thisBo, Object anotherBo) {
            if (thisBo.getClass() != anotherBo.getClass())
                throw new IllegalArgumentException("tow objects are not the same class type");
            Class<?> clazz = thisBo.getClass();

            while (clazz != Object.class) {
                Field[] fields = clazz.getDeclaredFields();
                Field idField;
                Object id;
                try {
                    AccessibleObject.setAccessible(fields, true);
                    for (Field field : fields) {
                        if ("id".equals(field.getName()) && field.get(thisBo) != null) {
                            id = field.get(thisBo);
                            idField = anotherBo.getClass().getDeclaredField("id");
                            idField.setAccessible(true);
                            idField.set(anotherBo, id);
                        }
                        Object obj1 = field.get(thisBo);
                        Object obj2 = field.get(anotherBo);
                        if (!ObjectUtils.equals(obj1, obj2)) {
                            return true;
                        }
                    }
                } catch (Exception e) {
                    System.out.print("faild");
                }
                clazz = clazz.getSuperclass();
            }
            return false;
        }

        public static boolean isDifferent(Object thisBo, Object anotherBo) {
            if (thisBo.getClass() != anotherBo.getClass())
                throw new IllegalArgumentException("tow objects are not the same class type");
            Class<?> clazz = thisBo.getClass();

            while (clazz != Object.class) {
                Field[] fields = clazz.getDeclaredFields();

                try {
                    AccessibleObject.setAccessible(fields, true);
                    for (Field field : fields) {
                        Object obj1 = field.get(thisBo);
                        Object obj2 = field.get(anotherBo);
                        if (!ObjectUtils.equals(obj1, obj2)) {
                            return true;
                        }
                    }
                } catch (Exception e) {
                    System.out.print("faild");
                }
                clazz = clazz.getSuperclass();
            }
            return false;
        }

        public static Object cloneObject(Object dst) {
            ByteArrayOutputStream byteOut = null;
            ObjectOutputStream objOut = null;
            ByteArrayInputStream byteIn = null;
            ObjectInputStream objIn = null;
            try {
                byteOut = new ByteArrayOutputStream();
                objOut = new ObjectOutputStream(byteOut);
                objOut.writeObject(dst);
                byteIn = new ByteArrayInputStream(byteOut.toByteArray());
                objIn = new ObjectInputStream(byteIn);
                return objIn.readObject();

            } catch (IOException e) {
                throw new RuntimeException("Clone Object failed in IO.", e);

            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Class not found.", e);

            } finally {
                try {
                    byteIn = null;
                    byteOut = null;
                    if (objOut != null)
                        objOut.close();
                    if (objIn != null)
                        objIn.close();
                } catch (IOException e) {

                }

            }

        }


    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值