H
H
hellcaster2019-02-21 14:52:08
Java
hellcaster, 2019-02-21 14:52:08

How to remove all elements from the first list from the second list?

For example I have

import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList<Character> first = new LinkedList<>();  // first = ['A', 'B', 'B', 'A']
    LinkedList<Character> second = new LinkedList<>();  // second = ['B', 'A']
  }
}

I need to remove all elements from the first list that are in the second one. At the end it should be:
first = ['A', 'B'],
second = [] or second = ['B', 'A']

But it is desirable not to use a loop. Is this possible or am I asking too much?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Osipov, 2019-02-21
@web_Developer_Victor

Here is some java8 if you don't tolerate cycles

List<String> listA = new ArrayList<String>(){{
      add("A");
      add("B");
      add("C");
      add("B");
      add("A");
    }};

    List<String> listB = new ArrayList<String>(){{
      add("A");
      add("B");
    }};

    listA.removeIf(s -> {
      if (listB.contains(s)) {
        listB.remove(s);
        return true;
      }
      return false;
    });

The result will be [C, B, A]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question