-1

I am working on a Minecraft Bukkit plugin for my server. Part of my plugin requires users to vote for a map. When they use the vote command (e.g. /vote <mapnumber>), their vote is stored in a HashMap (String Playername, Integer mapnumber) This is to detect if the user has already voted/wants to vote for a new map.

I then use a for loop to insert the votes into a new HashMap (Integer Mapnumber, Integer Numberofvotes). Here's where I'm stumped.

I am looking for a way to figure out which Mapnumber has the most notes.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Tristan
  • 65
  • 4
  • 9
  • 2
    Well, forget the fact that it's actually a map - you've got a collection of key/value pairs, and you want to find out which key has the highest value. So think how you might do that, iterating over the sequence and remembering the "best you've seen so far"... – Jon Skeet Oct 28 '13 at 12:14
  • 1
    possible duplicate of [Finding Key associated with max Value in a Java Map](http://stackoverflow.com/questions/5911174/finding-key-associated-with-max-value-in-a-java-map) – Alexis C. Oct 28 '13 at 12:15

2 Answers2

0

After building the hashmap, you could build another where key would be map number and value could be the frequency. Then all thats there to do is find max frequency.

HashMap<Integer,Integer> freq_map = new HashMap<Integer,Integer>();

int map_no=0,fr;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    map_no = pairs.getValue());
    if(map.contains(map_no)) fr = freq_map.get(map_no);
    else fr = 0;

    fr ++;
    freq_map.put(map_no,fr);
}

// to find max

int max = -1,temp;
int result = -1;
Iterator it = freq_map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    temp = pairs.getValue());

    if(temp>max){
        max = temp;
        result = pairs.getKey();
    }
}

System.out.println("Highest frequency = "+result);           
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
  • You should have a look at the [Java Naming Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html). – sp00m Oct 28 '13 at 12:27
0

Try this, it will give you the highest number of votes:

int maxNumberofVotes=(Collections.max(map.values()));
KeyNone
  • 8,745
  • 4
  • 34
  • 51
Pankaj Tiwari
  • 71
  • 2
  • 8