Please review my code:
public class Anagram {
public static void main(String args[]) {
String[] arr = { "abc", "cbc", "bcc", "dog", "god", "mary", "army",
"rty" };
HashMap<Integer, List<String>> mapList = new HashMap<Integer, List<String>>();
for (int i = 0; i < arr.length; i++) {
int hashcode = gethashcode(arr[i]);
if (mapList != null && mapList.get(hashcode) == null) {
List<String> list = new ArrayList<String>();
mapList.put(hashcode, list);
list.add(arr[i]);
} else {
List<String> list = mapList.get(hashcode);
list.add(arr[i]);
}
}
printMap(mapList);
System.out.println("Count=" + mapList.size());
}
private static void printMap(HashMap<Integer, List<String>> mapList) {
if (mapList != null && mapList.size() > 0) {
for (Integer key : mapList.keySet()) {
List<String> list = mapList.get(key);
System.out.print("[");
if (list != null && list.size() > 0) {
for (int k = 0; k < list.size(); k++) {
System.out.print(list.get(k) + " ");
}
}
System.out.print("]");
}
}
}
private static int gethashcode(String str) {
int hashcode = 0;
char ch[] = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (hashcode != 0) {
hashcode = hashcode + String.valueOf(ch[i]).hashCode();
} else {
hashcode = String.valueOf(ch[i]).hashCode();
}
}
return hashcode;
}
}
Output:
[mary army ][abc ][rty ][cbc bcc ][dog god ] Count=5