检查两个列表是否包含相同对象的最快方法

The fastest way to check if two lists contain the same object

我最近一直在处理一个问题,我必须等待几个小时才能得到正确的答案。 问题是这样的: 我有两个包含数千个元素的不同列表。 我想检查两个列表是否包含相同的元素,如果是的话我想将该元素添加到一个单独的列表中。 当我尝试使用列表中的少量元素时,该程序运行得非常好,但是当我尝试使用更多元素时,我必须等待数小时才能获得正确答案。

        List<Point> res1 = new LinkedList<>();
        for (Point value : w1) {
            System.out.println("Thread 1");
            Point a = value;
            for (Point point : w2) {
                if (a.equals(point)) {
                    System.out.println(Math.abs(a.x) + Math.abs(a.y));
                    res1.add(a);
                }

            }
        }

进行这种比较最快的方法是什么?

提前致谢

如果您使用 HashSet,您将免费获得一个非常高效的 contains 方法:

        HashSet hsw1 = new HashSet(w1); // turn first into a hashset
        List<Point> res1 = new LinkedList<>(w2); // load the second into new list
        res1.retainall(hsw1); // retain only values that are in the first as well