I am currently using the contains method belonging to the ArrayList class for making a search. Is there a way to make this search case insensitive in java? I found that in C
I would make it like so:
public boolean isStringInList(final List<String> myList, final String stringToFind) {
return myList.stream().anyMatch(s -> s.equalsIgnoreCase(stringToFind));
}
Looking at the Java API, there is no such method for contains.
But you could do at least two things:
Write your own contains method, which should iterate through your ArrayList entities, and do a manual check.
ArrayList<String> list = new ArrayList<String>();
...
containsIgnoreCase("a", list);
public boolean containsIgnoreCase(String str, ArrayList<String> list){
for(String i : list){
if(i.equalsIgnoreCase(str))
return true;
}
return false;
}
The contains
method is based on what the equals
method of the objects stored in your ArrayList
returns. So yes it is possible if you use objects where equals
uses a case insensitive comparison.
So you could for example use a class like this (code might still contain some typos)
public class CaseInsensitiveString{
private final String contents;
public CaseInsensitiveString( String contents){ this.contents = contents; }
public boolean equals( Object o ){
return o != null && o.getClass() == getClass() && o.contents.equalsIgnoreCase( contents);
}
public int hashCode(){
return o.toUpperCase().hashCode();
}
}
For java8
list.stream().anyMatch(s -> s.equalsIgnoreCase(yourString))
For < java8
Don't reinvent the wheel. Use well tested APIs. For your purpose use Apache Commons StringUtils.
From the Javadoc: Compares given string to a CharSequences vararg of searchStrings returning true if the string is equal to any of the searchStrings, ignoring case.
import org.apache.commons.lang3.StringUtils;
...
StringUtils.equalsAnyIgnoreCase(null, (CharSequence[]) null) = false
StringUtils.equalsAnyIgnoreCase(null, null, null) = true
StringUtils.equalsAnyIgnoreCase(null, "abc", "def") = false
StringUtils.equalsAnyIgnoreCase("abc", null, "def") = false
StringUtils.equalsAnyIgnoreCase("abc", "abc", "def") = true
StringUtils.equalsAnyIgnoreCase("abc", "ABC", "DEF") = true
If you're using Java 8, try:
List<String> list = ...;
String searchStr = ...;
boolean containsSearchStr = list.stream().filter(s -> s.equalsIgnoreCase(searchStr)).findFirst().isPresent();