Remove Matching Items from List Ignoring Case

In this tutorial, we will explore a technique for removing items from one list that match the items in another list, while ignoring case sensitivity.

In Java, there are several ways to remove elements out of a list. One way is to use the remove() method, which removes a specific item from the list. Another way is to use the removeAll() and clear() methods, which remove all the items from the list.

Here's a snippet of Java code that demonstrates how to remove all the items from a list if they match the items in 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 Example {

   public static void main(String[] args) {

      List list2 = Arrays.asList("It is Java", "It is Network", "It is Python", "It is C++", "It is HTML");

      List list1 = new ArrayList<>();
      list1.add("IT IS JAVA");
      list1.add("IT IS PYTHON");
      list1.add("IT IS HTML");
      list1.add("IT IS C++");
      list1.add("IT IS Example");

      if (!list1.isEmpty()) {

         Set set1 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

	 Set set2 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

	 // Removing multiple matched items by ignoring case from set1 list

	 // Keeping only the remaining items after removal in list1

      System.out.println("List 1 = " + list1);


The output of the above code is as follows:

List 1 = [IT IS Example]

In the above example, a check is performed to ensure that list1 is not empty before proceeding. Two sets, set1 and set2, are created using the TreeSet class, which automatically sorts the elements in ascending order. The String.CASE_INSENSITIVE_ORDER comparator is used to ignore the case sensitivity of the strings. All the elements from list1 are added to set1 using the addAll() method. All the elements from list2 are added to set2 using the addAll() method. The set1 set is modified to remove all the elements that are also present in set2 using the removeAll() method. The comparison is done ignoring the case sensitivity. The list1 list is modified to retain only the elements that are present in set1 using the retainAll() method. This operation keeps only the remaining items after removal in list1. Finally, the contents of list1 are printed using System.out.println().