簡體   English   中英

使用 Streams 檢查兩個相似列表之間的公共元素

[英]Checking common element between two similar Lists using Streams

比方說,我有 2 個相似的列表(雖然不一樣)。 例如:一個整數列表和另一個十六進制字符串列表(可以映射到整數),如何使用流查找兩個列表中同一索引處是否有任何公共元素?

讓我們考慮以下代碼:

List<Integer> l1 = List.of(11, 12, 13, 14, 15);
List<String> l2 = List.of("F", "E", "D", "C", "B")

boolean isCommon = checkIfCommonElementExists(l1, l2);
System.out.print("There's at least one common element at same index: " + isCommon);

在此示例中,兩個列表的第三個元素相同,即13OxD

如何使用 Streams 檢查(或查找)同一索引處是否存在任何此類公共元素並在第一次匹配時中斷(類似於 anyMatch())? 這是一個沒有流就可以解決的簡單問題,但是可以使用流來解決嗎?

你可以做類似下面的事情來檢查是否存在任何公共元素

private static boolean checkIfCommonElementExists(List<Integer> list1, List<String> list2) {
    return IntStream.range(0, Math.min(list1.size(), list2.size()))
            .anyMatch(i -> list1.get(i).equals(Integer.parseInt(list2.get(i),16)));
}

或類似下面的內容來獲取常見元素的索引

private static int[] findCommonElementIndexes(List<Integer> list1, List<String> list2) {
    return IntStream.range(0, Math.min(list1.size(), list2.size()))
            .filter(i -> list1.get(i).equals(Integer.parseInt(list2.get(i),16)))
            .toArray();
}

對於給定的例子:

List<Integer> l1 = List.of(11, 12, 13, 14, 15);
List<String> l2 = List.of("F", "E", "D", "C", "B");

boolean isCommon = checkIfCommonElementExists(l1, l2);
System.out.println("There's at least one common element at same index: " + isCommon);

System.out.println("Common indices" + Arrays.toString(findCommonElementIndexes(l1,l2)));

output:

There's at least one common element at same index: true
Common indices: [2]

暫無
暫無

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

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