Skip to content

Instantly share code, notes, and snippets.

@OlgaKulikova
Created November 10, 2014 14:11
Show Gist options
  • Save OlgaKulikova/294c49b3df157f70d956 to your computer and use it in GitHub Desktop.
Save OlgaKulikova/294c49b3df157f70d956 to your computer and use it in GitHub Desktop.
HashMapCounter
package arrayHashMap;
// Решить задачу подсчета повторяющихся элементов в массиве с помощью HashMap.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String[] arr = {"hello", "buy", "how are you", "hello", "hello", "buy"};
System.out.println(countSame(arr));
}
public static <T> Map<T, Integer> countSame(T[] arr) {
Map<T, Integer> map = new HashMap<>();
Integer count;
for (T i : arr) {
if (! map.containsKey(i)) {
map.put(i, 1);
} else {
count = 0;
for (T j : arr) {
if (j.equals(i)) {
count++;
}
}
map.remove(i);
map.put(i, count);
}
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment