Created
November 10, 2014 14:11
-
-
Save OlgaKulikova/294c49b3df157f70d956 to your computer and use it in GitHub Desktop.
HashMapCounter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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