Java Lambda - find if any String element of a list partially matches any element of another list

I have 2 lists String

A = {"apple", "mango", "pineapple", "banana", ... }

B = {"app", "framework",...}

      

What I'm looking for is any element from B, at least a partial match ( substring/contains/startsWith

) with any element A. For example, the 1st element of B 'app' partially matches at least one element 'apple'.

Other related StackOverflow topics don't account for 2 lists.

Is there any elegant way to express a solution using Java lambda?

I feel like this is a common problem in the search domain. So, if there is any help or interesting information on this topic, I'd love to get pointers.

+3


source to share


2 answers


Depending on what you mean by elegant, but try this:

List<String> r = list1
  .parallelStream()
  .filter( w1->{
      return list2
        .parallelStream()
        .anyMatch( w2->w1.contains(w2) ); 
      }
   )
  .collect(Collectors.toList());

      



anyMatch

(and filter

) can be short-circuited and will interrupt the flow of the second list after finding the first match w1.contains(w2)

and return true if found, which will give some efficiency. Use this to filter the first stream. Do it in parallel threads.

+5


source


You can link the streams of the two List<String>

and filter with String.contains()

or any other condition you want to use ( substring()

, startsWith()

).

Then you could map a couple of strings that did the condition correctly into an array String

:

List<String> listOne = Arrays.asList("apple", "mango", "pineapple", "framework");
List<String> listTwo = Arrays.asList("app", "frame");

List<String[]> values = listOne.stream()
    .flatMap(x -> listTwo.stream()
        .filter(y -> x.contains(y))
        .map(y -> {
            return new String[] { x, y };
        }))
    .collect(Collectors.toList());

for (String[] array : values) {
    System.out.println(Arrays.toString(array));
}

      



Output:

[apple, app]

[pineapple, attachment]

[framework, frame]

+2


source







All Articles