Search code examples
javalistjava-8java-7

How a save in a list the elements of a first list that are not contained in a second list with duplicate values?


I have a problem with a heuristic for Virtual Graph where I have to count the elements of numbers from two integer lists: I have to put in a list the numbers of the first one and the numbers that are not in the second list.

I've tried with two addAll and a removeAll(secondList) and it works but when the lists have duplicates It doesn't work because removes the duplicate element too:

        //Test lists
        List<Integer> ls1 = Arrays.asList(1,1,2,3);
        List<Integer> ls3 = Arrays.asList(1,3);
        List<Integer> s = new ArrayList<>();

        s.addAll(ls1);
        System.out.println("Add " + ls1);
        s.addAll(ls3);
        System.out.println("Add " + ls3);
        System.out.println("New list" + s);
        s.removeAll(ls3);
        System.out.println("Expected value (1,2)");
        System.out.println("Result List " + s);

The new list is [1, 1, 2, 3, 1, 3] and the expected output is [1,2] but the actual output is only 2.


Solution

  • Remove elements present in ls2 from ls1 as :

    List<Integer> ls1 = Arrays.asList(1, 1, 2, 3);
    List<Integer> ls2 = Arrays.asList(1, 3);
    List<Integer> s = new ArrayList<>(ls1);
    ls2.forEach(s::remove);