Ron Arel
Ron Arel

Reputation: 371

How to only remove one item from list with duplicates?

I have a list: (x, y, y,z)

I have another list: (x, y)

You want to remove the items from the 1st list that belong also in the 2nd list.

Ex: I want the result to be (y,z)

How do I do this?

EDIT: If I use removeAll. The example list returns (z)

Upvotes: 1

Views: 232

Answers (3)

Opsse
Opsse

Reputation: 1911

This solution seems acceptable.

List<String> one = new ArrayList<>();
one.add("x");
one.add("y");
one.add("y");
one.add("z");
List<String> two = new ArrayList<>();
two.add("x");
two.add("y");

for (String s : two)
{
    one.remove(s);
}

System.out.println("one : " + one);

The output :

one : [y, z]


List.remove(Object o) documentation :

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).


Note: The algorithm complexity is O(n*m), avoid to do it with 2 very big lists (where n and m are list size).

Upvotes: 1

Anisuzzaman Babla
Anisuzzaman Babla

Reputation: 7480

You can do this in many ways. Here is some examples.

List<String> one = new ArrayList<String>();
    one.add("x");
    one.add("y");
    one.add("y");
    one.add("z");
List<String> two = new ArrayList<String>();
    two.add("x");
    two.add("y");

1. Using Lambda

two.forEach((i)->one.remove(i));
System.out.println(one);

Output: [y, z]

2. Apache Commons

Collection<Integer> result = CollectionUtils.subtract(one, two);
System.out.println(one);

Output: [y, z]

Upvotes: 1

user8959091
user8959091

Reputation:

Check this:

    ArrayList<String> list1 = new ArrayList<String>();
    list1.add("Maria");
    list1.add("Nick");
    list1.add("Nick");
    list1.add("Joe");

    ArrayList<String> list2 = new ArrayList<String>();
    list2.add("Maria");
    list2.add("Nick");

    for (String x : list2) {
        int index = list1.indexOf(x);
        if (index >= 0) {
            list1.remove(index);
        }
    }

Upvotes: 0

Related Questions