简体   繁体   English

检查字符串是否在字符串的 ArrayList 中

[英]Check if a String is in an ArrayList of Strings

How can I check if a String is there in the List ?如何检查List是否存在String

I want to assign 1 to temp if there is a result, 2 otherwise.如果有结果,我想将1分配给temp ,否则为2

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;
temp = bankAccNos.contains(no) ? 1 : 2;

The List interface already has this solved. List接口已经解决了这个问题。

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

More can be found in the documentation about List . 有关List的文档中可以找到更多内容。

    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
*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元素 C 在 ArrayList 中可用 元素 H 在 ArrayList 中不可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM