Java 8字符串比较

Pra*_*gam 2 java string arraylist java-8 java-stream

我有两个字符串列表.我想检查一个列表中的任何字符串是否在另一个列表中可用.使用下面的方法失败了.

请让我知道一个更好的方法

List<String> mylist = Arrays.asList(stringArray1);
List<String> items = Arrays.asList(stringArray2);

return mylist.stream().anyMatch(t->items.stream().anyMatch(t::contains));
Run Code Online (Sandbox Code Playgroud)

Jac*_* G. 6

如果你想找到如果任何元素mylist存在items,你可以先转itemsSet:

Set<String> setOfItems = new HashSet<>(items);
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地迭代mylist并检查是否包含任何元素setOfItems.

mylist.stream().anyMatch(setOfItems::contains);
Run Code Online (Sandbox Code Playgroud)

这使您的O(n * k)问题到O(n + k)这里nk是的大小mylistitems分别.

  • 你仍然可以使用单行,`mylist.stream().anyMatch(new HashSet <>(items):: contains);`.由于这种优化只能为较大的集合付出代价,因此甚至可以使用阈值,例如`static final int HASH_THRESHOLD = 30; ... mylist.stream().anyMatch((items.size()<HASH_THRESHOLD?items:new HashSet <>(items)):: contains);` (2认同)