之前的做法有bug
public class NewGroupContact {
//http://www.fgdsb.com/2015/01/25/group-contacts/
// http://www.1point3acres.com/bbs/thread-148422-1-1.html
// http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=192328&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26searchoption%255B3046%255D%255Bvalue%255D%3D2%26searchoption%255B3046%255D%255Btype%255D%3Dradio&page=1
public static void main(String[] args) {
HashMap<String/* string value */, Integer/* type */> st = new HashMap<>();
HashMap<Integer/* type */, Set<String>/* type */> ts = new HashMap<>();
// String[][] A = { { "John", "john@gmail.com", "john@fb.com" },
// { "Dan", "dan@gmail.com", "+1234567" },
// { "john123", "+5412312", "john123@skype.com" },
// { "john1985", "+5412312", "john@fb.com" },
// { "Dan12", "+1234567", "dan@fb.com" },
// { "Shaohui", "+4125194763", "sguo@fb.com" }};
String[][] A = { { "x", "y", "z" }, { "Shaohui" }, { "a", "b" }, { "k", "z" }, { "m", "a" },
{ "Shaohui", "+4125194763", "sguo@fb.com", "x" } };
int code = 0;
for (int i = 0; i < A.length; i++) {
int c = -1;
Set<Integer/*type*/> groupings = new HashSet<Integer>();
for (int j = 0; j < A[i].length; j++) {
String s = A[i][j];
if (st.containsKey(s)) {
int value = st.get(s);
groupings.add(value);
c = Math.max(c, value);
}
}
if (c == -1) {
c = code++;
} else {
groupings.remove(c);
Set<String> set = ts.get(c);
for (Integer k : groupings) {
if (ts.containsKey(k)) {
Set<String> strs = ts.get(k);
set.addAll(strs);
ts.remove(k);
}
}
}
for (int j = 0; j < A[i].length; j++) {
String s = A[i][j];
st.put(s, c);
if (ts.containsKey(c)) {
ts.get(c).add(s);
} else {
ts.put(c, new HashSet<String>());
ts.get(c).add(s);
}
}
}
for (Map.Entry<Integer, Set<String>> entry: ts.entrySet()) {
System.out.print("group: " + entry.getKey() + " [");
for (String str: entry.getValue()) {
System.out.print(" "+str+" ");
}
System.out.println("]");
}
}
}