Remove Multiple String Items from a List by Ignoring Case in Java

There are many methods to remove items from a list in Java. The remove () method is used to remove a particular element from the list. The removeAll() and clear() methods are used to remove all the elements of the list.

The program below demonstrates how you can remove all the items from a list that matches all the items from another list by ignoring case:


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class ListItemsRemovalExample {

	public static void main(String[] args) {
		List<String> dataList = new ArrayList<>();
		dataList.add("IT IS JAVA");
		dataList.add("IT IS PYTHON");
		dataList.add("IT IS HTML");
		dataList.add("IT IS C++");
		dataList.add("IT IS Example");
		
		List<String> outputItems = removeMultipleMatchingItems(dataList);
		System.out.println("Output items = " + outputItems);
	}

	private static List<String> removeMultipleMatchingItems(List<String> dataList) {
		if (!dataList.isEmpty()) {
			
			Set<String> dataSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
			dataSet.addAll(dataList);

			List<String> stringsToRemoveList = Arrays.asList("It is Java", "It is Network", "It is Python", "It is C++",
					"It is HTML");
            Set<String> stringsToRemoveSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
			stringsToRemoveSet.addAll(stringsToRemoveList);

			// Removing multiple matched items by ignoring case from dataSet list
			dataSet.removeAll(stringsToRemoveSet);

			// Keeping in dataList only the remaining items after removal
			dataList.retainAll(dataSet);
		}
		return dataList;

	}

}

The above code gives the following output:

Output items = [IT IS Example]

Here, in the above example code, we have named our class ListItemsRemovalExample and imported the necessary packages for the program. We have created two lists in the program. Both lists contain multiple same string items. The elements of both lists are then added to TreeSet in order to ignore case. TreeSet Class is a part of Java's collection framework that has built-in support for case insensitive element search. Then, removeAll() method is called to delete all the string items that exists in both Set objects. Next, the retainAll() method of the List object is used to keep the remaining string items on the Set object after removal of matched items.