java 获取两个list集合里面中不相同的元素

在项目开发中,经常会对比不同的集合,获取里面不相同的元素,一般会用到好几种方法,这里算是一种,mark一下。

public static List<Integer> getDiffrent(List<Integer> list1, List<Integer> list2) {
        long st = System.nanoTime();
        List<String> diff = new ArrayList<String>();
        List<Integer> dif = new ArrayList<Integer>();
        List<String> l1=new ArrayList<>();
        List<String> l2=new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            l1.add(list1.get(i)+"");
        }
        for (int i = 0; i < list2.size(); i++) {
            l2.add(list2.get(i)+"");
        }
        List<String> maxList = l1;
        List<String> minList = l2;
        if(list2.size()>list1.size())
        {
            maxList = l2;
            minList = l1;
        }
        Map<String,Integer> map = new HashMap<String,Integer>(maxList.size());
        for (String string : maxList) {
            map.put(string, 1);
        }
        for (String string : minList) {
            if(map.get(string)!=null)
            {
                map.put(string, 2);
                continue;
            }
            diff.add(string);
        }
        for(Map.Entry<String, Integer> entry:map.entrySet())
        {
            if(entry.getValue()==1)
            {
                diff.add(entry.getKey());
            }
        }
        for (int i = 0; i < diff.size(); i++) {
            BigDecimal bd = new BigDecimal(diff.get(i));
            dif.add(Integer.valueOf(bd.toPlainString()));
        }
        return dif;

    }

你可能感兴趣的:(算法)