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

余生长醉 提交于 2019-12-11 19:45:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!