Retain & remove elements/ nodes of linkedlist collection (Java/ example)

  • Given a LinkedList collection in java, we would like retain certain elements or nodes of linkedlist.
    • We would like to remove rest of elements from linkedlist.
  • The LinkedList class extends AbstractSequentialList and implements the List interface.
  • LinkedList class have following method to retain elements/ nodes.
    • boolean retainAll(Collection<?> c)
      Retains only the elements in this list that are contained in the specified collection.

Program – Retain & remove elements/ nodes of linked list in java

package org.learn.collection.list.linkedlist;
 
import java.util.LinkedList;
 
public class DemoRetainInOfLinkedList {
 
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList<>();
        linkedList.add("squash");
        linkedList.add("archery");
        linkedList.add("golf");
        linkedList.add("judo");
        linkedList.add("canoe");
        linkedList.add("squash");
        linkedList.add("diving");
        linkedList.add("judo");
        System.out.println("1. Demo of retain & remove elements - Linkedlist: ");
        demoRetainAll(linkedList);
    }
 
    private static void demoRetainAll(LinkedList linkedList) {
        // [squash, archery, golf, judo, canoe, canoe, diving, squash, bowling, judo]
        System.out.println("2. original LinkedList:" + linkedList);
        LinkedList retainSportsList = new LinkedList<>();
        retainSportsList.add("golf");
        retainSportsList.add("diving");
        retainSportsList.add("archery");
        retainSportsList.add("badminton");
        System.out.println("3. Elements to be retained:"+retainSportsList);
        linkedList.retainAll(retainSportsList);
        //[archery, golf, diving]
        System.out.println("4. Elements retained in original linkedlist: " + linkedList);
    }
}

Output – Retain & remove elements/ nodes of linked list in java

1. Demo of retain & remove elements - Linkedlist:
2. Original LinkedList:[squash, archery, golf, judo, canoe, squash, diving, judo]
3. Elements to be retained:[golf, diving, archery, badminton]
4. Elements retained in original linkedlist: [archery, golf, diving]