Showing posts with label java stream api. Show all posts
Showing posts with label java stream api. Show all posts

Thursday, 18 May 2023

Java arraylist contains case insensitive

There are several ways to check if an element exists in an ArrayList in a case-insensitive way in Java.

Using String.equalsIgnoreCase()

The simplest way is to use the String.equalsIgnoreCase() method. This method compares two strings for equality, ignoring case differences.

For example, the following code will check if the string "hello" exists in the ArrayList list in a case-insensitive way:

boolean found = list.contains(new String("hello").toLowerCase())

Using a custom function

You can also create a custom function to check if an element exists in an ArrayList in a case-insensitive way. This function can be used as follows:

boolean found = containsIgnoreCase(list, "hello");

The following is an example of a custom function that can be used to check if an element exists in an ArrayList in a case-insensitive way:

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

Using the Stream API

If you are using Java 8 or later, you can also use the Stream API to check if an element exists in an ArrayList in a case-insensitive way. The following code shows how to do this:

boolean found = list.stream().anyMatch(str::equalsIgnoreCase);

In this code, the anyMatch() method is used to check if any element in the stream matches the given string. The str::equalsIgnoreCase method is a method reference that calls the equalsIgnoreCase() method on the given string.

Conclusion

These are just a few of the ways to check if an element exists in an ArrayList in a case-insensitive way in Java. The best way to do this will depend on your specific needs.