如何在java中找到第一个匹配元素时迭代2arraylist并退出

我有 2 个数组列表,两者都有一些共同的值。


我试过 for 循环,做 while 循环,但对我没有任何作用


我想要第一个匹配/公共元素并返回相同的元素并在那里退出代码本身


boolean good = true; 

for (int i = 0; i <1Val.size(); i ++) { 

   if (!(2Val.contains(1Val.get(i)))) { 

      System.out.println("Matched---" +quoteVal.get(i)); 

      good = false; break; 

   } 


互换的青春
浏览 130回答 4
4回答

梵蒂冈之花

您可以只使用 Java Streams 来解决这个问题:boolean&nbsp;good&nbsp;=&nbsp;val1.stream().anyMatch(val2::contains);如果你需要第一个匹配的值,你可以使用这个:Optional<String>&nbsp;firstMatch&nbsp;=&nbsp;val1.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(val2::contains) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.findFirst();用于Optional.isPresent()检查是否找到匹配项并Optional.get()获取实际值。要提高大型列表的性能,请使用集合 for&nbsp;val2。的时间复杂度为O&nbsp;(1)Set.contains()。

精慕HU

也许您想使用流&nbsp; &nbsp; List<String> list1 = Arrays.asList("a","b","c","d","e");&nbsp; &nbsp; List<String> list2 =&nbsp; Arrays.asList("b","e");&nbsp; &nbsp; //gets the list of common elments&nbsp; &nbsp; List<String> common = list1.stream().filter(s -> list2.contains(s)).collect(Collectors.toList());&nbsp; &nbsp; if (common.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("no common elements");&nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("common elements");&nbsp; &nbsp; &nbsp; &nbsp; common.forEach(System.out::println);&nbsp; &nbsp; }&nbsp; &nbsp; //just the check if any equal elements exist&nbsp; &nbsp; boolean commonElementsExist = list1.stream().anyMatch(s -> list2.contains(s));&nbsp; &nbsp; //3rd version get the first common element&nbsp; &nbsp; Optional<String> firstCommonElement = list1.stream().filter(s -> list2.contains(s)).findFirst();&nbsp; &nbsp; if(firstCommonElement.isPresent()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("the first common element is "+firstCommonElement.get());&nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("no common elements");&nbsp; &nbsp; }

繁星点点滴滴

如果其中一个数组列表小于您应该在 for 循环中使用该特定列表的大小。for(int i = 0; i < 1Val.size(); i++){&nbsp; &nbsp; &nbsp; if(2val.contains(1Val.get(i))){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return true; // common value found&nbsp; &nbsp; &nbsp; }}return false; // common value not found

扬帆大鱼

试试这个代码for (int i=0;i<arrayList2.size();i++) {for (int j=0;j<arrayList1.size(); j++) {if(al2.get(i)equals(al1.get(j))){// do something// you can add them to the new arraylist to process further or type break; to break from the loop{}&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java