Site icon

Retain or remove String objects/ elements of arraylist collection (java /example)

  1. Given an arraylist collection of String objects in java.
  2. We would like to retain certain elements of arraylist (and would like to remove rest of elements of arraylist).
  3. Arraylist has following method to retain elements.
    • boolean retainAll(Collection<?> c)
      • Retains only the elements in this list that are contained in the specified collection.
  4. We will create array list containing number of sports.
    • OrignalArrayList:[archery, badminton, canoe, boxing, diving, beach volleyball]
  5. We would like to retain elements in original array list, which are present in retainSportsList.
    • e.g. retainSportsList: [soccer, judo, archery, badminton]
  6. The output of OrignalArrayList.retainAll(retainSportsList) should return [archery, badminton]
    • i.e. All elements of retainSportsList will be retained in OrignalArrayList (if present in OriginalArrayList).

1. Retain/remove String objects/elements of arraylist collection in java

package org.learn.collection.list.arrayList;

import java.util.ArrayList;

public class DemoRetainInOfArrayList {

	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<>();
		arrayList.add("archery");
		arrayList.add("badminton");
		arrayList.add("canoe");
		arrayList.add("boxing");
		arrayList.add("diving");
		arrayList.add("beach volleyball");

		System.out.println("Demo of retain method: ");
		demoRetainAll(arrayList);
	}

	private static void demoRetainAll(ArrayList<String> arrayList) {
		System.out.println("1. Orignal ArrayList:" + arrayList);
		ArrayList<String> retainSportsList = new ArrayList<>();
		retainSportsList.add("soccer");
		retainSportsList.add("judo");
		retainSportsList.add("archery");
		retainSportsList.add("badminton");
		System.out.println("2. Elements in retainSportsList:"+retainSportsList);
		arrayList.retainAll(retainSportsList);
		//What ever element presents in source list, will be retained.
		System.out.println("3. Retained elements in arraylist: " + arrayList);
	}
}

2. Retain/remove String objects/elements of arraylist collection (example)

Demo of retain method: 
1. Orignal ArrayList:[archery, badminton, canoe, boxing, diving, beach volleyball]
2. Elements in retainSportsList:[soccer, judo, archery, badminton]
3. Retained elements in arraylist: [archery, badminton]
Exit mobile version