Check if a String is in an ArrayList of Strings
167,150
Solution 1
temp = bankAccNos.contains(no) ? 1 : 2;
Solution 2
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
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
Author by
abhi
Interested in Java and web based application development. Technologies - C++, Java, Web Development, Servlets, JSP, JSF1.2, JSF2.0, Richfaces 3.3.3, Richfaces 4.0, Swing, Spring-Security, Oracle 10g & 11g, PostgresSQL etc.
Updated on October 20, 2021Comments
-
abhi over 2 years
How can I check if a
String
is there in theList
?I want to assign
1
totemp
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;