Xitrum Xitrum - 14 days ago 7
Java Question

Finding similar words in multiple string (Intersection)

For example,

String a = "cat dog monkey";
String b = "cat cow monkey";
String c = "cat dog duck";


I wonder whether is there any fast and efficient way to do it in Java, in order to find the intersected words of multiple strings, in this case will be "cat".

Answer

I'd split each string to an array, convert it to a Set and use the retainAll method:

String a = "cat dog monkey";
String b = "cat cow monkey";
String c = "cat dog duck";

Set<String> aSet = new HashSet<>(Arrays.asList(a.split(" ")));
Set<String> bSet = new HashSet<>(Arrays.asList(a.split(" ")));
Set<String> cSet = new HashSet<>(Arrays.asList(a.split(" ")));

Set<String> result = new HashSet<>(aSet);
result.retainAll(bSet);
result.retainAll(cSet);