Search code examples
javamultithreadinglistperformancecomparison

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


I've been dealing with a problem lately where i have to wait for hours to get the right answer. The problem is this: I have two different lists that have thousands of elements. I want to check if both lists contain the same element and if soo i want to add that element in a separate list. When i try with a small amount of elements in the lists, the program works perfectly fine but when i try with more elements, i have to wait for hours to get the right answer.

        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);
                }

            }
        }

What is the fastest way to do this kind of comparing?

Thanks in advance


Solution

  • If you use HashSet you get a very efficient contains method free of charge:

            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