简体   繁体   中英

java: check if any element in array 1 is present in array 2

I am fairly new to java streams and wonder whether there is an easy solution using java streams to check if any element in array 1 is also present in array 2

example:

array1 = ["banana","apple","cat"]
array2 = ["toast","bread","pizza","banana"]
--> return true

array1 = ["banana","apple","cat"]
array2 = ["toast","bread","pizza"]
--> return false

Thanks!

Just use Collections.disjoint. This method checks if any elements of the both arrays are common.

Collections.disjoint(Arrays.asList(array1), Arrays.asList(array2))

I think this works for you. However, I had to convert the second array to a set check if element exists in an array. I think that's more intuitive than a for loop iteration.

String[] arr1 = new String[]{"a", "b"};
String[] arr2 = new String[]{"a", "d"};
Set<String> strings = Set.of(arr2);
boolean result = Stream.of(arr1).anyMatch(strings::contains);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM