2016-11-30 43 views
-2

我有兩個字符串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)。發佈您嘗試過的代碼以及收到的錯誤。儘可能具體,因爲它會導致更好的答案。 –

回答

0

使用此代碼:

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

相關問題