如何在另一个ArrayList中查找元素并在新Collection中添加匹配的元素?

问题描述:

我有两个字符串ArrayLists:A字和B的句子。我需要找到包含ArrayList A元素的ArrayList B的元素,并将它们添加到新集合C中。如何在另一个ArrayList中查找元素并在新Collection中添加匹配的元素?

主要问题是,如何同时迭代两个集合并查找B是否包含A的元素?

+0

你可以使用嵌套的'for'循环... – brso05

+0

所以,你需要与句子匹配的是在集合C中的话吗? –

+2

欢迎来到SO。请看[旅游](http://stackoverflow.com/tour)。您可能还想检查[我可以询问哪些主题](http://stackoverflow.com/help/on-topic),以及[如何提出一个好问题](http://stackoverflow.com/help/)如何提问)和[完美问题](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/),以及如何创建[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。发布您尝试过的代码以及收到的错误。尽可能具体,因为它会导致更好的答案。 –

使用此代码:

public static void main(String[] args) { 
    ArrayList<String> a=new ArrayList<String>(); 
    ArrayList<String> b=new ArrayList<String>(); 

    //new Collection 
    ArrayList<String> c=new ArrayList<String>(); 

    a.add("hi"); 
    a.add("there"); 
    a.add("how"); 
    a.add("are"); 

    b.add("how are you?"); 
    b.add("I'm fine!"); 
    b.add("What about you"); 
    b.add("Hello you there?"); 

    for(String s: b){ 
     for(String s2: a){    
      if(s.contains(s2)){ 
       c.add(s); 
       break; 
      } 
     } 
    } 
    System.out.println(c); 
} 

输出:[how are you?, Hello you there?]

+0

@ thatfella16,你想要这个吗? –

+0

绝对!非常感谢! – thatfella16