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 Ord = new ArrayList();
public void leggTilOrd(String ord){
if (!Ord.contains(ord)){
Ord.add(ord);
}
}
解决方案
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 list = new ArrayList<>();
public void addIfNotPresent(String str) {
if (list.stream().noneMatch(s -> s.equalsIgnoreCase(str))) {
list.add(str);
}
}