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);
}
}
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);
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With