Site icon

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

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]
Exit mobile version