Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an ArrayList contains a certain String while being case insensitive

Tags:

java

arraylist

How can i search through an ArrayList using the .contains method while being case insensitive? I've tried .containsIgnoreCase but found out that the IgnoreCase method only works for Strings.

Here's the method I'm trying to create:

 private ArrayList<String> Ord = new ArrayList<String>(); 

 public void leggTilOrd(String ord){
     if (!Ord.contains(ord)){
         Ord.add(ord);
     }
 }
like image 243
Ragnar Johansen Avatar asked Oct 12 '16 06:10

Ragnar Johansen


2 Answers

You will need to iterate over the list and check each element. This is what is happening in the contains method. Since you are wanting to use the equalsIgnoreCase method instead of the equals method for the String elements you are checking, you will need to do it explicitly. That can either be with a for-each loop or with a Stream (example below is with a Stream).

private final List<String> list = new ArrayList<>();

public void addIfNotPresent(String str) {
    if (list.stream().noneMatch(s -> s.equalsIgnoreCase(str))) {
        list.add(str);
    }
}
like image 65
Aaron Davis Avatar answered Sep 20 '22 18:09

Aaron Davis


If you are using Java7, simply override the contains() method,

public class CastInsensitiveList extends ArrayList<String> {
    @Override
    public boolean contains(Object obj) {
        String object = (String)obj;
        for (String string : this) {
            if (object.equalsIgnoreCase(string)) {
              return true;
            }
        }
        return false;
    }
}

If you are using Java 8.0, using streaming API,

List<String> arrayList = new ArrayList<>();
arrayList.stream().anyMatch(string::equalsIgnoreCase);
like image 27
Kris Avatar answered Sep 22 '22 18:09

Kris