Help the world stop coronavirus! Stay home!

Prev Next

Java / List and its implementations

Difference between removeAll() and retailAll() methods in Java collection.

removeAll method removes the collection elements (List, Set, Vector also Collection) that exist in the specified collection of elements.

public class ArrayListEx {

	public static void main(String[] args) {
		List<String> myList = new ArrayList<>();
		myList.add("A");
		myList.add("B");
		myList.add("C");
		myList.add("D");
		List<String> mySubList = myList.subList(2, 3);
		System.out.println("List content is " + myList);
		myList.removeAll(mySubList);
		System.out.println("List content  after remove is" + myList);

	}

}

Output:
List content is [A, B, C, D]
List content  after remove is [A, B, D]

retainAll method retains the collection elements (List, Set, Vector also Collection) that exist in the specified collection of elements and it removes all other elements.

public class ArrayListEx {

	public static void main(String[] args) {
		List<String> myList = new ArrayList<>();
		myList.add("A"); myList.add("B");myList.add("C");myList.add("D");
		
		List<String> mySubList = myList.subList(2, 3);
		System.out.println("List content is " + myList);
		myList.retainAll(mySubList);
		System.out.println("List content  after retaining is " + myList);

	}

}

Output:
List content is [A, B, C, D]
List content  after retaining is [C]

❤Cash Back At Stores you Love !!!❤

Earn your $10 reward when you make your first purchase through Ebates by signing up with clicking below button.

Ebates Coupons and Cash Back

More Related questions...

Show more question and Answers...

Map and its implementations

Comments & Discussions