Okay, Although i am scared to post this answer as i think it is very crude but still i will go ahead and post it. Fingers crossed :).
retainAll
uses equals
internally and since string
is a final
class
we cannot manipulate it but we can create a wrapper
around it and provide a custom equals
implementation. But this adds to the space complexity.
Here is what i did (used contains
in equals method).
public class FindAlike{
public static void main(String[] args) {
ArrayList<StringWrapper> list1 = new ArrayList<StringWrapper>(Arrays.asList(new StringWrapper("John"),new StringWrapper("Mary")
,new StringWrapper(" Mr. John Marsh"),new StringWrapper("Mrs. Mary Dsouza"),new StringWrapper("abc"),new StringWrapper("xyz")));
ArrayList<StringWrapper> list2 = new ArrayList<StringWrapper>(Arrays.asList(new StringWrapper("John"),new StringWrapper("Mary"),
new StringWrapper("Tim"),new StringWrapper("Sam")));
list1.retainAll( list2 );
System.out.println( list1 );
}
private static class StringWrapper{
private String value;
public StringWrapper(String value) {
this.value = value;
}
public String getValue(){
return this.value;
}
@Override
public boolean equals(Object obj) {
return this.value.contains(((StringWrapper)obj).getValue());
}
@Override
public String toString() {
return this.value;
}
}
}
For the given data i got the following output -
[John, Mary, Mr. John Marsh, Mrs. Mary Dsouza]