Get the difference between two arraylist with duplicate elements

Mido :

I want to get the difference between two lists. And this is what I am doing.

oldList = [1,1,2,2,3,3,4,4]
newList = [1,2,3,5]

List<Integer> add = new ArrayList<>(newList);
List<Integer> remove = new ArrayList<>(oldList);
add.removeAll(oldList);
remove.removeAll(newList);

The result I want

add = [5]
remove = [1,2,3,4,4]

But removeAll() remove all duplicate element. The results that I received

add = [5]
remove = [4,4]

How do I get the add and remove list? Thanks.

SomeGuy :

You're going to have to write some of your own code. This can't be done using only the Java Collection libraries alone.

import java.util.ArrayList;

public class MyList<T> extends ArrayList<T>{

    public MyList(){
        super();
    }

    public void specialRemoveAll(T[] list) {
        for (T element : list) {
            remove(element); // This only removes the first entry that matches 'element', not all matches
        }
    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400446&siteId=1