我有两个字符串列表。 我想检查一个列表中的任何字符串是否在另一个列表中可用。 使用了以下失败的方法。
请告诉我一个更好的方法
List<String> mylist = Arrays.asList(stringArray1);
List<String> items = Arrays.asList(stringArray2);
return mylist.stream().anyMatch(t->items.stream().anyMatch(t::contains));
最佳答案
如果要查找mylist
中的任何元素是否存在于items
中,可以先将items
变成一个Set
:
Set<String> setOfItems = new HashSet<>(items);
然后,您可以简单地遍历 mylist
并检查是否有任何元素包含在 setOfItems
中。
mylist.stream().anyMatch(setOfItems::contains);
这将您的 O(n * k)
问题降为 O(n + k)
,其中 n
和 k
分别是 mylist
和 items
的大小。
关于Java 8 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51479735/