ArrayList contains case sensitivity

I am currently using the contains method, which belongs to the ArrayList class, to perform a search. Is there a way to make this search case insensitive in java? I found that in C # you can use OrdinalIgnoreCase. Is there a java equivalent or another way to do this? Thank.

+57
java arraylist
Jan 05 2018-12-12T00:
source share
18 answers

You can use this in the same way as if you used any other ArrayList. You can pass this list to other code, and the external code should not understand any classes of string wrappers.

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; } } 
+63
Jan 05 2018-12-12T00:
source share

If you are using Java 8, try:

 List<String> list = ...; String searchStr = ...; boolean containsSearchStr = list.stream().filter(s -> s.equalsIgnoreCase(searchStr)).findFirst().isPresent(); 
+31
Mar 03 '14 at 21:45
source share

In Java8 using anyMatch

 List<String> list = Arrays.asList("XYZ", "ABC"); String matchingText = "xYz"; boolean isMatched = list.stream().anyMatch(matchingText::equalsIgnoreCase); 
+21
Aug 03 '16 at 15:33
source share

Traditionally, you can develop your own logic to compare strings stored in an ArrayList . There are several ways to do this, as shown below.

 public boolean containsCaseInsensitive(String strToCompare, ArrayList<String>list) { for(String str:list) { if(str.equalsIgnoreCase(strToCompare)) { return(true); } } return(false); } 

Why you should not use some direct and convenient methods, for example, 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)); 

Will compare two different sets, ignoring case and return true , in this particular situation, and your comparison will work without any problems.

+13
Jan 06
source share

Looking at the Java API , there is no such method for this.

But you could do at least two things:

  • Override the equals method in an ArrayList with your own or equalsIgnoreCase (str)
  • Write your own contains method, which should go through your ArrayList objects 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; } 
+9
Jan 05 '12 at 23:40
source share

Assuming you have an ArrayList<String>

On how I can do this, one could create a very lightweight wrapper class around the string and override equal and hash codes to ignore case using equalsIgnoreCase() where possible. Then you will have an ArrayList<YourString> . This is a kind of ugly idea.

+7
Jan 05 '12 at 23:35
source share

You can use IterableUtils and Predicate from collections4 (apache).

 List<String> pformats= Arrays.asList("Test","tEst2","tEsT3","TST4"); Predicate<String> predicate = (s) -> StringUtils.equalsIgnoreCase(s, "TEST"); if(IterableUtils.matchesAny(pformats, predicate)) { // do stuff } 

IterableUtils (collections4): org.apache.commons.collections4.IterableUtils.html

+3
Feb 17 '16 at 13:56
source share

The contains method is based on what returns the equals method of the objects stored in your ArrayList . So yes, it is possible if you use objects where equals uses case-insensitive comparison.

Thus, you can, for example, use such a class (the code may 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(); } } 
+2
Jan 05 2018-12-12T00:
source share

The ArrayList contains () method checks for equality by calling the equals () method for the object you provide (NOT the objects in the array). Therefore, a slightly hacky way is to create a wrapper class around a String object, for example:

 class InsensitiveStringComparable { private final String val; public InsensitiveStringComparable(String val) { this.val = val; } @Override public boolean equals(Object x) { if (x == this) return true; else if (x == null) return false; else if (x instanceof InsensitiveStringComparable) return ((InsensitiveStringComparable) x).val.equalsIgnoreCase(val); else if (x instanceof String) /* Asymmetric equals condition */ return val.equalsIgnoreCase((String) x); else return false; } @Override public int hashCode() { return val.toUpperCase().hashCode(); } } 

Then you can use it to run the test. Example "manual" test example:

 public class Test { public static void main(String[] args) { ArrayList<Object> a = new ArrayList<Object>(); a.add("test"); System.out.println(a.contains(new InsensitiveStringComparable("TEST"))); System.out.println(a.contains(new InsensitiveStringComparable("tEsT"))); System.out.println(a.contains(new InsensitiveStringComparable("different"))); } } 
+2
Jan 05 '12 at 23:40
source share

Another solution:

 public class IgnorecaseList extends ArrayList<String>{ @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public int indexOf(Object o) { if(o instanceof String){ for (int i = 0; i < this.size(); i++) { if(((String)o).equalsIgnoreCase(get(i))){ return i; } } } return -1; } } 

contains() method uses indexOf ... In this resolution, you can also find out where the string is. list.add("a") β†’ list.indexOf("A") == 0 or list.indexOf("A") == 0 ..

You should also consider using a set instead of a list.

+2
Jan 6 2018-12-12T00:
source share

For java8

list.stream (). anyMatch (s β†’ s.equalsIgnoreCase (yourString))

For <java8

  • as suggested by Aaron J Lang above
  • Or, if you know the case of your list (all upper / all lower), then convert the search string to the appropriate case before comparing
+2
Mar 15 '17 at 10:38 on
source share

In my case, since all my lines in the ArrayList are lowercase, I just run the String method. toLowerCase () in the contains () parameter. Like this:

 If (yourArrayList.contains (parameterInput.toLowerCase()) { // your code here } 

As you can see, you can make oposite if yout arrayList has upperCase strings:

 If (yourArrayList.contains (parameterInput.toUpperCase ()) { // your code here } 

Using this approach, you do not need to redefine anything. The exception is when your List array has a combination of upper and lower case.

+2
Mar 29 '17 at 18:31
source share

There is no need for an additional function, the desired results can be achieved by casting the compared strings in both upper and lower case

(I know this was suggested in the comments, but not fully presented as an answer)

Ex: ignores case when filtering JList content based on input provided with JTextField:

 private ArrayList<String> getFilteredUsers(String filter, ArrayList<User> users) { ArrayList<String> filterUsers = new ArrayList<>(); users.stream().filter((user) -> (user.getUsername().toUpperCase().contains(filter.toUpperCase()))).forEach((user)-> { filterUsers.add(user.getUsername()); }); this.userList.setListData(filterUsers.toArray()); return filterUsers; /** * I see the redundancy in returning the object... so even though, * it is passed by reference you could return type void; but because * it being passed by reference, it a relatively inexpensive * operation, so providing convenient access with redundancy is just a * courtesy, much like putting the seat back down. Then, the next * developer with the unlucky assignment of using your code doesn't * get the proverbially dreaded "wet" seat. */ } 
+1
Jul 14 '15 at 10:11
source share

This is the best way to convert a list item to lowercase. After the conversion, you will use the contains method. as

 List<String> name_list = new ArrayList<>(); name_list.add("A"); name_list.add("B"); 

Create a string list using the name_list above

 List<String> name_lowercase_list = new ArrayList<>(); for(int i =0 ; i<name_list.size(); i++){ name_lowercase_list.add(name_list.get(i).toLowerCase().toString()); } for(int i =0 ; i<name_list.size(); i++){ String lower_case_name = name_list.get(i).toLowerCase().toString(); if(name_list.get(i).contains(your compare item) || name_lowercase_list.get(i).contains(your compare item) ){ //this will return true } } 
0
Aug 10 '16 at 11:43
source share

I would do this:

 public boolean isStringInList(final List<String> myList, final String stringToFind) { return myList.stream().anyMatch(s -> s.equalsIgnoreCase(stringToFind)); } 
0
Nov 02 '17 at 19:21
source share

If you do not want to create a new function, you can try this method:

 List<String> myList = new ArrayList<String>(); //The list you're checking String wordToFind = "Test"; //or scan.nextLine() or whatever you're checking //If your list has mix of uppercase and lowercase letters letters create a copy... List<String> copyList = new ArrayList<String>(); for(String copyWord : myList){ copyList.add(copyWord.toLowerCase()); } for(String myWord : copyList){ if(copyList.contains(wordToFind.toLowerCase()){ //do something } } 
0
Nov 17 '17 at 4:11
source share

Do not reinvent the wheel. Use proven APIs. For your purpose, use Apache Commons StringUtils .

From Javadoc: compares the given string with charSequences vararg searchStrings, returning true if the string is equal to any of the searchStrings elements, 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 
0
Oct 30 '18 at 7:55
source share
-one
Jan 05 '12 at 23:35
source share



All Articles