24

Can I somehow tell the array.contains() method to not make the lookup case sensitive?

List<String> data = Arrays.asList(
  "one", Two", "tHRee"); //lots of entries (100+)

data.contains("three");
membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

50

contains just check if an object is present in the List. So you can't do a case insensitive lookup here, because "three" is a different object than "Three".

A simple approach to solve this would be

public boolean containsCaseInsensitive(String s, List<String> l){
     for (String string : l){
        if (string.equalsIgnoreCase(s)){
            return true;
         }
     }
    return false;
  }

and then

containsCaseInsensitive("three", data);

Java 8+ version:

public boolean containsCaseInsensitive(String s, List<String> l){
        return l.stream().anyMatch(x -> x.equalsIgnoreCase(s));
    }
Averroes
  • 4,168
  • 6
  • 50
  • 63
-1

it will require you to write your own contains() method. pointers for custom contains():

  1. iterate over all the elements in the list.
  2. compare the parameter string with all the values in
  3. to make comparison case-insensitive be sure to apply any of toLowerCase or toUpperCase on BOTH parameter and the current element.

    List list; public boolean contains(String str){

       for(int i=0;i<list.size();i++){
           if(list.elementAt(i).toLowerCase().Equals(str.toLowerCase())) return true;
       }
    return false;
    }
    
Ankit
  • 6,554
  • 6
  • 49
  • 71
  • 3
    Not an efficient answer. You are converting `str` to lower case N times (once for each element of `list`), and you are converting each item of `list` to lower case every time you call this method. If you are going to the trouble of writing your own method, just use `equalsIgnoreCase` and skip all of the allocations. – John Hart Jan 04 '16 at 19:26