问题
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!
回答1:
Just use Collections.disjoint. This method checks if any elements of the both arrays are common.
Collections.disjoint(Arrays.asList(array1), Arrays.asList(array2))
回答2:
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);
来源:https://stackoverflow.com/questions/57000384/java-check-if-any-element-in-array-1-is-present-in-array-2