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.");
   }
}
                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"));
                        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");
}   
                        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