This program goes round the loop 100000 times.Each time round the loop, it
picks a random number from 1 to 10.
When first unique number is picked, containsKey(r) returns false. A new
Counter for this number is created and put into the HashMap. The next time
same number is picked, containsKey(r) returns true, because a key
object Integer(firstnumber) has already been put in the HashMap and
increments the counter to count how many times this number was picked..
..
import java.util.*;
class Counter {
int j = 1;
public String toString() {
return Integer.toString(j);
}
}
public class RandomTest {
public static void main(String[] args) {
HashMap hm = new HashMap();
for(int j = 0; j < 100000; j++) {
Integer r = new Integer((int)(Math.random() * 10));
if(hm.containsKey(r))
((Counter)hm.get(r)).j++;
else
hm.put(r, new Counter());
}
System.out.println(hm);
}
}
..
The output is in a form of:
{2=9874, 4=9896, 8=10160, 9=10125, 6=9975, 1=9932, 3=10108, 7=9894, 5=10085,
0=9951}
Is there an easy way of sorting the map so it will display the ones that
appear the most time first, such as:
{8=10160, 9=10125, 3=10108, 5=10085, 0=9951..etc}
I think I would somehow have to move through the sequence of these objects
and than sort them but I am not sure of the easiest way. I'd prefer to use
as much as built in feautures..
Thanks for any suggestions.