ArrayList contains case sensitivity
You can use this exactly like you'd use any other ArrayList. You can pass this List out to other code, and external code won't have to understand any string wrapper classes.
public class CustomStringList3 extends ArrayList<String> {
@Override
public boolean contains(Object o) {
String paramStr = (String)o;
for (String s : this) {
if (paramStr.equalsIgnoreCase(s)) return true;
}
return false;
}
}
In Java8, using anyMatch
List<String> list = Arrays.asList("XYZ", "ABC");
String matchingText = "xYz";
boolean isMatched = list.stream().anyMatch(matchingText::equalsIgnoreCase);
If you're using Java 8, try:
List<String> list = ...;
String searchStr = ...;
boolean containsSearchStr = list.stream().filter(s -> s.equalsIgnoreCase(searchStr)).findFirst().isPresent();
Traditionally, you can develop your own logic to compare strings held by an ArrayList
. There may be several ways to do so like the one shown below.
public boolean containsCaseInsensitive(String strToCompare, ArrayList<String>list)
{
for(String str:list)
{
if(str.equalsIgnoreCase(strToCompare))
{
return(true);
}
}
return(false);
}
Why shouldn't be used some direct and convenient ways like a SortedSet as shown below with a case insensitive comparator?.
Set<String> a = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
a.add("A");
a.add("B");
a.add("C");
Set<String> b = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
b.add("a");
b.add("b");
b.add("c");
System.out.println(b.equals(a));
Would compare two different sets ignoring case and return true
, in this particular situation and your comparision would work without any issue.