我有兩個字符串ArrayLists:A
字和B
的句子。我需要找到包含ArrayList A
元素的ArrayList B
的元素,並將它們添加到新集合C
中。如何在另一個ArrayList中查找元素並在新Collection中添加匹配的元素?
主要問題是,如何同時迭代兩個集合並查找B
是否包含A
的元素?
我有兩個字符串ArrayLists:A
字和B
的句子。我需要找到包含ArrayList A
元素的ArrayList B
的元素,並將它們添加到新集合C
中。如何在另一個ArrayList中查找元素並在新Collection中添加匹配的元素?
主要問題是,如何同時迭代兩個集合並查找B
是否包含A
的元素?
使用此代碼:
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?]
@ thatfella16,你想要這個嗎? –
絕對!非常感謝! – thatfella16
你可以使用嵌套的'for'循環... – brso05
所以,你需要與句子匹配的是在集合C中的話嗎? –
歡迎來到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)。發佈您嘗試過的代碼以及收到的錯誤。儘可能具體,因爲它會導致更好的答案。 –