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# it is possible to use OrdinalIgnoreCase. Is there a java equivalent, or another way to do this? Thanks.
If you also need the String back in the original case, contains() will only help to indicate that it is present in the list. A HashMap could retrieve the original string given a uppercase or lowercase string, and would have a much better search characteristic (but it would not retain the original order of the strings).
In this example, we will show you how to check HashSet contains element case insensitive in Java. contains() method of Collection interface returns true if this set contains the specified element. But the problem is contains() method only check the equality of element (case sensitive).
The solution is not to make the elements case-insensitive (which technically would mean reimplementing String--one cannot extend it because it is final--with a wrapper class whose equals and compareTo methods are case-insensitive), but rather to make the comparison case-insensitive.
HashSet's contains() method is case sensitive and does not allow the use of comparators. We could use TreeSet instead of HashSet which allow Comparator thus facilitating case-insensitive search and comparison. Using the comparator String. CASE_INSENSITIVE_ORDER we could perform case ignored search.
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; } }
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