Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - arraylist check if element exits here ignore the case

Tags:

java

Hi i have the arraylist it stores the string values. I want to check the some string is exists in the list or not. Here i want ignore the case sensitive.

code

public static ArrayList< String > arrFoodItems = new ArrayList< String >();

if(arrFoodItems.contains("string"))

        {
            System.out.println("already available in the List.");
        }
        else
        {
            System.out.println("Not available");
        }   

It's working fine. But in the following example it fails. How to do it without using loops. Example: List contains: "Rice, Chicken,..." Now you are check for "rice" is exits in the list. In this case we are getting "not exists".

Don't using this

for(int i=0; i < arrFoodItems.size(); i++)
{

   if(arrFoodItems.get(i)..equalsIgnoreCase(string))
   {
        System.out.println("already available in the List.");
   }
}
like image 442
naresh Avatar asked Nov 29 '22 14:11

naresh


2 Answers

You could put all your strings in a TreeSet with a custom Comparator that ignores the case:

List<String> list = Arrays.asList("Chicken", "Duck");
Set<String> set=  new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
set.addAll(list);
System.out.println(set.contains("Chicken")); //true
System.out.println(set.contains("chicken")); //true

For more complex strategies / locale, you can also use a Collator:

final Collator ignoreCase = Collator.getInstance();
ignoreCase.setStrength(Collator.SECONDARY);

List<String> list = Arrays.asList("Chicken", "Duck");
Set<String> set=  new TreeSet<String>(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return ignoreCase.compare(o1, o2);
    }
});
set.addAll(list);
System.out.println(set.contains("Chicken"));
System.out.println(set.contains("chicken"));
like image 108
assylias Avatar answered Dec 05 '22 07:12

assylias


Looping through the elements is what contains does for you so if you don't want to use a loop, its best not to use an ArrayList.

Without using a different collection your best option is to use

FOUND: {
    for(String item: arrFoodItems) {
       if (item.equalsIgnoreCase(string)) {
          System.out.println(string+" already available in the List.");
          break FOUND;
       }
    }
    System.out.println(string + " not available");
}   
like image 24
Peter Lawrey Avatar answered Dec 05 '22 06:12

Peter Lawrey