import java.util.HashMap;
public class Test {
private static void writeOccurences(int array[]) {
HashMap<Integer,Integer> occurences = new HashMap<Integer,Integer>();
//Count occurences
for (int number : array) {
int currentCount = (occurences.containsKey(number) ? occurences.get(number).intValue() : 0);
occurences.put(number, currentCount + 1);
}
//Write out occurences
for (Integer key : occurences.keySet()) {
System.out.println(key + " forekom " + occurences.get(key) + " gange");
}
}
public static void main(String args[]) {
int values[] = {6, 2366, 56, 7, 7, 2, 6, 7, 235, 263464, 7542, 1566, -23857, -6581, 1566, 56};
writeOccurences(values);
}
}
...giver følgende output:
robert-desktop:~/code $ javac Test.java
robert-desktop:~/code $ java Test
-6581 forekom 1 gange
2 forekom 1 gange
-23857 forekom 1 gange
1566 forekom 2 gange
263464 forekom 1 gange
235 forekom 1 gange
6 forekom 2 gange
7 forekom 3 gange
7542 forekom 1 gange
56 forekom 2 gange
2366 forekom 1 gange
robert-desktop:~/code $
Indlæg senest redigeret d. 11.01.2008 08:59 af Bruger #2695