Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a String is in an ArrayList of Strings

How can I check if a String is there in the List?

I want to assign 1 to temp if there is a result, 2 otherwise.

My current code is:

Integer temp = 0; List<String> bankAccNos = new ArrayList<String>();//assume list contains values String bankAccNo = "abc"; for(String no : bankAccNos)     if(no.equals(bankAccNo))         temp = 1; 
like image 334
abhi Avatar asked Apr 18 '12 11:04

abhi


People also ask

How do you check if a string is in a ArrayList?

ArrayList. contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.

How do you check if a string is present in a list of strings in Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you check if a list of string contains a particular string?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));


2 Answers

temp = bankAccNos.contains(no) ? 1 : 2; 
like image 117
jazzytomato Avatar answered Sep 24 '22 03:09

jazzytomato


The List interface already has this solved.

int temp = 2; if(bankAccNos.contains(bakAccNo)) temp=1; 

More can be found in the documentation about List.

like image 43
Angelo Fuchs Avatar answered Sep 25 '22 03:09

Angelo Fuchs