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]

More Related questions...

Show more question and Answers...


Comments & Discussions