Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Searching for elements in a list is a standard operation when working with ArrayList. The contains() method lets us know if a list object has the element we're looking for.

In this tutorial, we'll explore how to search a string in an ArrayList<String> object case-insensitively.

2. Introduction to the Problem

Internally, the ArrayList.contains() method uses the equals() method to determine whether the list has a given element. If all elements in an ArrayList are strings, i.e., when working with ArrayList<String>, the contains() method searches the given string case-sensitively. Let's understand it quickly through an example.

Let's say we have a List object containing six strings:

List<String> LANGUAGES = Arrays.asList("Java", "Python", "Kotlin", "Ruby", "Javascript", "Go");

When we check if LANGUAGES contains “jAvA”, the contains() method reports false, as “jAvA” doesn't equal “Java”:

String searchStr = "jAvA";
boolean result = LANGUAGES.contains(searchStr);
assertFalse(result);

In this tutorial, let's learn a few approaches for searching a string in an ArrayList<String> instance without caring about the case.

For simplicity, we'll use unit test assertions to verify if the solutions work as expected.

So next, let's see them in action.

3. Using the Stream API

Java Stream API provides many handy interfaces, allowing us to handle Collections as streams easily. It's available on Java 8 and later versions.

For example, we can use Stream‘s anyMatch() method to do a case-insensitive string search:

String searchStr = "koTliN";
boolean result = LANGUAGES.stream().anyMatch(searchStr::equalsIgnoreCase);
assertTrue(result);

As we can see in the example above, we search the string “koTliN” in the LANGUAGES list. Then, if we run it, the test passes.

It's worth mentioning that the searchStr::equalsIgnoreCase we pass to the anyMatch() method is a method reference. The searchStr.equalsIgnoreCase() method will be called for each string element in the stream.

4. Creating a Utility Method

We've seen that the Stream API can solve the problem straightforwardly. However, we cannot use the Stream API if our Java version is older than 8. In this case, a classic approach to solving the problem is to create a utility method:

public class IgnoreCaseSearchUtil {
    public static boolean ignoreCaseContains(List<String> theList, String searchStr) {
        for (String s : theList) {
            if (searchStr.equalsIgnoreCase(s)) {
                return true;
            }
        }
        return false;
    }
}

As the code above shows, we check each string element in the given list in a for-loop. Once an element equals searchStr case-insensitively, the method returns true immediately without checking further elements in the list.

Next, let's create a test to verify if it works as expected:

String searchStr = "ruBY";
boolean result = IgnoreCaseSearchUtil.ignoreCaseContains(LANGUAGES, searchStr);
assertTrue(result);

This time, we searched the string “ruBY” in the list. Again, the test passes if we give it a run.

5. Creating a Subclass of ArrayList<String>

So far, we've learned two approaches to determining whether an ArrayList<String> object contains a given string ignoring case. Both solutions are pretty easy to understand. However, if we need to perform this operation quite often in our project, we must call the utility method or Stream API's anyMatch() method many times.

If this is the case, we probably want to create a particular ArrayList<String> type, which supports the case-insensitive contains() method natively.

So next, let's create a subclass of ArrayList<String>:

public class IgnoreCaseStringList extends ArrayList<String> {

    public IgnoreCaseStringList() {

    }

    public IgnoreCaseStringList(Collection<? extends String> c) {
        super(c);
    }

    @Override
    public boolean contains(Object o) {
        String searchStr = (String) o;
        for (String s : this) {
            if (searchStr.equalsIgnoreCase(s)) {
                return true;
            }
        }
        return false;
    }

}

As we can see in the code above, the IgnoreCaseStringList class inherits ArrayList<String>. We've created two constructors to initialize an IgnoreCaseStringList instance more easily. Moreover, to make IgnoreCaseStringList support case-insensitive contains(), we've overridden the contains() method. The implementation is not new to us. It's pretty similar to the utility method we've learned.

Next, let's test whether IgnoreCaseStringList works:

String searchStr = "pYtHoN";
List<String> ignoreCaseList = new IgnoreCaseStringList(LANGUAGES);
boolean result = ignoreCaseList.contains(searchStr);
assertTrue(result);

As we can see, after initializing an IgnoreCaseList instance, we can simply call the contains() method to search the given string case-insensitively. When we execute the test above, it passes. So, IgnoreCaseStringList does the job neatly.

It's worth mentioning that the IgnoreCaseList approach brings another benefit. It makes the containsAll() method case-sensitive too. This is because the containsAll() method is implemented in the AbstractCollection class, a supertype of ArrayList. Further, it internally calls the contains() method:

public boolean containsAll(Collection<?> c) {
    Iterator var2 = c.iterator();
    Object e;
    do {
        if (!var2.hasNext()) {
            return true;
        }
        e = var2.next();
    } while(this.contains(e));
    return false;
}

Finally, let's write a test to verify it:

boolean resultContainAll = ignoreCaseList.containsAll(Arrays.asList("pYtHon", "jAvA", "koTliN", "ruBY"));
assertTrue(resultContainAll);

On the other hand, if we want the Stream API and the utility method approaches also to support the case-sensitive containsAll() feature, we must implement it on our own, for example, by adding another utility method.

6. Conclusion

In this article, we've explored how to perform case-insensitive searching in ArrayList<String>. We've learned three approaches to solving the problem through examples.

As usual, all code snippets presented in the article are available over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments