For example, I have:

import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList first = new LinkedList(); // first = ['A', 'B', 'B', 'A'] LinkedList second = new LinkedList(); // second = ['B', 'A'] } } 

I need to remove all items from the first list that are in the second. In the end should be:

first = ['A', 'B'],
second = [] or second = ['B', 'A']

But it is desirable not to use a cycle. Is this possible or do I ask too much?

    2 answers 2

    Go through the loop and delete the items you encountered:

     LinkedList first = new LinkedList(); // first = ['A', 'B', 'B', 'A'] first.addAll(Arrays.asList("A", "B", "B", "A")); LinkedList second = new LinkedList(); // second = ['B', 'A'] second.addAll(Arrays.asList("B", "A")); for (Object o : second) { first.remove(o); } System.out.println(first); // [B, A] 

    Instead of a loop, you can use the construction of streams-api (@Russtam, thanks for the hint):

     second.forEach(first::removeFirstOccurrence); System.out.println(first); // [B, A] 

    First, the first B ( ['A', 'B', 'A'] ) will be deleted, after A ( ['B', 'A'] )

    • second.forEach (first :: removeFirstOccurrence); - Russtam pm
    • @Russtam, stream-api is simply divine :) - gil9red February 3:14 pm
     int index = Collections.indexOfSubList(first, second); if (index!=-1) { List<String> list1 = first.subList(0, index); List<String> list2 = first.subList(index + second.size(), first.size()); list1.addAll(list2); first = list1; }