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.
You can achieve this in many ways. One of the ways is using **Set**.

First, split **m1** the characters by (comma) and add it to **HashSet**. Then split the **m2** characters and add it to **ArrayList**. Now by the for loop try to add the **ArrayList** characters to **HashSet**. You will get false from the add method (`Set.add()`) if it is not added (because the character is already there). If you get false print the character or add it to another ArrayList.

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

        Set<String> set = new HashSet<>(Arrays.asList(m3.split(",")));
        List<String> list = Arrays.asList(m2.split(","));
        for (String s : list) {
            if (!set.add(s)) {
                System.out.println(s);
            }
        }

```

Result will be T and E