欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取两个List的不同元素 博客分类: Java 两个List的不同元素 

程序员文章站 2024-03-16 12:25:28
...
    /**
     * 获取两个List的不同元素
     * 
     * @param list1
     * @param list2
     * @return
     */
    private static List<String> getDiffrent4(List<String> list1, List<String> list2)
    {

        long st = System.nanoTime();

        Map<String, Integer> map = new HashMap<String, Integer>(list1.size() + list2.size());
        List<String> diff = new ArrayList<String>();

        List<String> maxList = list1;
        List<String> minList = list2;

        if (list2.size() > list1.size())
        {
            maxList = list2;
            minList = list1;
        }

        for (String string : maxList)
        {
            map.put(string, 1);
        }

        for (String string : minList)
        {
            Integer cc = map.get(string);
            if (cc != null)
            {
                map.put(string, ++cc);
                continue;
            }

            map.put(string, 1);
        }

        for (Map.Entry<String, Integer> entry : map.entrySet())
        {
            if (entry.getValue() == 1)
            {
                diff.add(entry.getKey());
            }
        }

        System.out.println("getDiffrent4 total times " + (System.nanoTime() - st));

        return diff;

    }