2

I have two list of strings. I want to check if any string from one list is available in another list. Have used below approach which fails.

Please let me know a better approach

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

return mylist.stream().anyMatch(t->items.stream().anyMatch(t::contains));
4
  • retainAll may be? Commented Jul 23, 2018 at 13:17
  • what do you want to obtain btw? All the entries that are common? Commented Jul 23, 2018 at 13:18
  • @Eugene I want a boolean value if the any one value is available in another list Commented Jul 23, 2018 at 13:35
  • in this case, myList.stream().anyMatch(items::contains) should do the job Commented Jul 23, 2018 at 13:36

1 Answer 1

6

If you want to find if any element in mylist exists in items, you can first turn items into a Set:

Set<String> setOfItems = new HashSet<>(items);

Then, you can simply iterative over mylist and check if any element is contained in setOfItems.

mylist.stream().anyMatch(setOfItems::contains);

This brought your O(n * k) problem down to O(n + k) where n and k are the sizes of mylist and items, respectively.

Sign up to request clarification or add additional context in comments.

2 Comments

G: Your a Rockstar, Thank you
You still can use a one-liner, mylist.stream().anyMatch(new HashSet<>(items)::contains);. Since this optimization only pays off for larger collections, it’s even possible to use a threshold, e.g. static final int HASH_THRESHOLD = 30; … mylist.stream().anyMatch((items.size() < HASH_THRESHOLD? items: new HashSet<>(items))::contains);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.