Question: I have some strings defined in my Java application, like so:

```
 m3 = "T, V, E";
 m2 = "T, W, E";

```

as an example.

Now I need to check, which parts of the strings match. So in this case, I would want a string `m4`, containing `T, E`, as a result.

In that case for example:

```
m1 = "A, S";
m3 = "T, V, E";

```

i would want an empty (but declared) string.

Or is there a better way, to do it with another method then with strings? I'm actually declaring those strings by hand. Would an array be better? If yes, how could I do it with arrays?

Answer: 
In Java 8 you can proceed as below : 

```
    String s1 = "T,V,E";
    String s2 = "T,W,E";

    List<String> l1 = Arrays.asList(s1.split(","));
    List<String> l2 = Arrays.asList(s2.split(","));

    List<String> result = l1.stream().filter(l2::contains).collect(Collectors.toList());

    System.out.println(String.join(",", result));

```

The result is "T,E" as expected.
If all your `String` follows this pattern : `..., ..., ....` , you could split them and filter only each String that is contained in the two arrays.  

You can then collect them into a `List` and join them with `,` :

```
List<String> commonStrings = Arrays.stream(m2.split(",\\s"))
      .flatMap(s-> Arrays.stream(m3.split(",\\s"))
      .filter(s2.equals(s)))          
      .collect(Collectors.toList());

String joinedString = String.join(",", commonStrings);

```

Note that this code doesn't return the exact number of equals occurrences in the two `String`s.  

So if one `String` contains two `A` and the other one `A`, you will get two `A` in the result.  

If it doesn' matter and you want to get only distinct `String`, you can invoke `distinct()` before `collect()`.  

Otherwise, to return the exact number of equals occurrences, during the processing, as soon as a `String` part is consumed (`A` for example) as the two parts are equal in the two `String`s, you could create new `String`s from the actual `String`s but by removing this `String` part .