You can try something like this using HashSet
import java.util.HashSet;
import java.util.Set;
public class QuickTester {
public static void main(String[] args) {
String s1 = "happy";
String s2 = "elephant";
Set set1 = new HashSet();
Set set2 = new HashSet();
for(char c : s1.toCharArray()) {
set1.add(c);
}
for(char c : s2.toCharArray()) {
set2.add(c);
}
// Stores the intersection of set1 and set2 inside set1
set1.retainAll(set2);
for(char c : set1) {
System.out.print(" " + c);
}
System.out.println("\nTotal number of common characters: "
+ set1.size());
}
}
Refer to retainAll on how the intersection of 2 sets is done.
Input Strings:
happy
elephant
Output:
p a h
Total number of common characters: 3