Core Java

Case Insensitive String Handling in Java Lists

Checking if a List contains a string element while ignoring cases can be a common requirement, especially when dealing with user input or data retrieval from external sources. Java offers multiple approaches to achieve this, each with its advantages. This article will explore various methods to perform case-insensitive string element checks in lists.

1. Overview of the Problem

In Java application development, encountering the need to search for a string element within a list while disregarding case sensitivity is a common challenge. Consider a scenario where we are developing a contact management application where users can search for contacts by their names. However, user inputs can vary widely in capitalization.

For instance, a user might search for “Smith” as “smith“, “sMith“, or “SMITH“. To ensure a seamless user experience, it’s crucial to implement a search functionality that disregards case sensitivity, allowing users to find contacts regardless of capitalization inconsistencies. This underscores the significance of exploring methods to perform case-insensitive string element checks in Java lists.

1.1 ArrayList.contains Method

The contains() method in the List interface is handy for verifying if a List holds a particular element. By default, the contains() method uses equals() method internally to confirm a match and return true if the element is found. However, this search is performed in a case-sensitive manner.

List<String> list = List.of("Avocado", "Pumpkin", "Spinach", "Asparagus");

assertTrue(list.contains("Avocado"));
assertFalse(list.contains("avocado"));

To address this issue, we can utilize the traditional loop method along with equalsIgnoreCase() or toLowerCase() method, or opt for the Java Streams API.

2. Method 1: Traditional Loop Iteration

2.1 Using with equalsIgnoreCase()

Traditional loop iteration provides a straightforward solution using the String class which provides the equalsIgnoreCase() method:

public class StringComparisonExample {

    public static boolean containsIgnoreCase(List<String> list, String searchString) {
        for (String str : list) {
            if (str.equalsIgnoreCase(searchString)) {
                return true;
            }
        }
        return false;
    }
}

Here’s what the method above does:

  • It takes two parameters:
    • List<String> list: This is a list of strings that the method will search through.
    • String searchString: This is the string that the method will search for within the list.
  • Inside the method, there’s a loop that iterates over each string (str) in the provided list.
  • For each string in the list, it checks if the string, when compared in a case-insensitive manner (equalsIgnoreCase), is equal to the searchString.
  • If a match is found, meaning the current string in the list is equal to the searchString ignoring case, the method returns true, indicating that the searchString is present in the list.
  • If the loop completes without finding a match, the method returns false, indicating that the searchString is not present in the list.

To verify whether the containsIgnoreCase() method works as expected, we test it in the main method of the Java class:

    public static void main(String[] args) {

        List<String> list = List.of("Avocado", "Pumpkin", "Spinach", "Asparagus");

        String searchString = "pumpkin";

        if (containsIgnoreCase(list, searchString)) {
            System.out.println("List contains the string \"" + searchString + "\" ignoring case.");
        } else {
            System.out.println("List does not contain the string \"" + searchString + "\" ignoring case.");
        }
    }

Running the program gives the following output:

Fig 1.0: Java list search case insensitive example output using Loop and equalsIgnoreCase() method
Fig 1.0: Java list search case insensitive example output using Loop and equalsIgnoreCase() method

2.2 Manual Iteration with Lowercase Conversion

This method iterates through the list, converting both the search string and each list element to lowercase before comparison using the toLowerCase() method:

   public static boolean containsIgnoreCase(List<String> list, String searchString) {
        for (String str : list) {
            if (str.toLowerCase().equals(searchString.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

The above method Iterates through each element in the list and compares it with the search string after converting both to lowercase.

3. Method 3: Using Java Streams

The Java Stream API provides a more elegant way to perform operations on collections. We can utilize the anyMatch() method along with a case-insensitive comparison to check if the list contains a string element:

    public static boolean containsIgnoreCase(List list, String element) {
        return list.stream()
                .anyMatch(str -> str.equalsIgnoreCase(element));
    }

Here is a break down of the code listing above:

  • list.stream() method converts the List into a stream.
  • .anyMatch(...) method tests whether any elements of the stream match the given predicate.
  • str -> str.equalsIgnoreCase(element) is a lambda expression that defines the predicate. It checks whether the current element (str) of the stream when compared to ignoring case (equalsIgnoreCase), is equal to the element.
  • The result of anyMatch is returned, which is true if at least one element in the list matches the given element (ignoring case), otherwise false.

4. Conclusion

In Java, checking if a list contains a string element while ignoring case can be accomplished using various techniques. Whether leveraging the Stream API for concise operations or sticking to traditional loop iteration for simplicity, we have multiple options to choose from based on our specific requirements and preferences.

5. Download the Source Code

This was an example of Case Insensitive String Handling in Java Lists.

Download
You can download the full source code of this example here: java list search case insensitive

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button