簡體   English   中英

使用Stream比較兩個集合 - anyMatch

[英]Comparing two collections using Stream - anyMatch

我想比較list2任何對象是否存在於list1

我可以迭代兩個列表並使用.contains()比較所有元素,但我想知道是否沒有更有效的方法。 我找到了這個 ,我正在嘗試實現建議的方法:

List<Item> list1;
List<Item> list2;

boolean anyMatch = list1.stream().anyMatch(x -> x.equals(list2.stream()));
System.out.println(anyMatch);

當我這樣做的時候,即使我期待true ,我也會不斷變得false 怎么會?

根據您的評論,您有兩個列表, list1list2 您想知道list1是否包含list2中的至少一個元素。

隨着流API,你可以獲取Streamlist2 然后,調用anyMatch(predicate)返回此流的一個元素是否與給定謂詞匹配,在這種情況下,測試該元素是否包含在list1

boolean anyMatch = list2.stream().anyMatch(list1::contains);

這使用方法引用作為謂詞。

通過將list1轉換為Set ,可以獲得更好的性能,從而保證了常量查找:

boolean anyMatch = list2.stream().anyMatch(new HashSet<>(list1)::contains);

雖然@Tinaki的答案是正確的, 但這是另一種更簡潔的方法(它不使用Stream.anyMatch()方法):

boolean anyMatch = !Collections.disjoint(list1, list2);

這使用Collections.disjoint()方法,當兩個集合沒有共同的元素時返回true

Tunaki關於性能的評論也適用於此:為了獲得更好的性能,最好的方法是將list1轉換為HashSet ,因為其contains()方法的平均值為O(1) Collections.disjoint()方法實際檢查其任何參數是否為Set並迭代不是Set 所以在你的情況下,你所要做的就是從list1創建一個HashSet

boolean anyMatch = !Collections.disjoint(new HashSet<>(list1), list2);

注意:畢竟,我的答案只比Tunaki的短了5個字符:)

  • 使用Java 8流API
boolean isAnyMatch = list2.stream().anyMatch(list1::contains);
  • 使用Collection類方法
boolean isAnyMatch = !Collections.disjoint(new HashSet(list1), list2);

無論如何在比較之前將列表轉換為設置將提供更快的輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM