Check if a String is in an ArrayList of Strings

JavaStringListArraylist

Java Problem Overview


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;

Java Solutions


Solution 1 - Java

temp = bankAccNos.contains(no) ? 1 : 2;

Solution 2 - Java

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.

Solution 3 - Java

	List list1 = new ArrayList();
	list1.add("one");
	list1.add("three");
	list1.add("four");
	
	List list2 = new ArrayList();
	list2.add("one");
	list2.add("two");
	list2.add("three");
	list2.add("four");
	list2.add("five");
	
	
	list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));
	

The output is:

two
five

Solution 4 - Java

*public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      if(aList.contains("C"))
         System.out.println("The element C is available in the ArrayList");
      else
         System.out.println("The element C is not available in the ArrayList");
      if(aList.contains("H"))
         System.out.println("The element H is available in the ArrayList");
      else
         System.out.println("The element H is not available in the ArrayList");
   }
}*

The Output will be:

> The element C is available in the ArrayList The element H is not > available in the ArrayList

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionabhiView Question on Stackoverflow
Solution 1 - JavajazzytomatoView Answer on Stackoverflow
Solution 2 - JavaAngelo FuchsView Answer on Stackoverflow
Solution 3 - JavaAbhiView Answer on Stackoverflow
Solution 4 - JavaAdam reubenView Answer on Stackoverflow