Xitrum Xitrum - 1 year ago 108
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download