0

Hi Stackoverflow genii, I have a question about sorting a TreeMap by value, not key. It's for an assignment, so I have to do it this way, and I don't necessarily need someone to type out an answer for me, just a tip on what I'm doing wrong. Here's my code:

import java.security.KeyStore.Entry;
import java.util.Scanner;
import java.util.TreeMap;

public class Assignment2 {
    public static void main(String[] args) {
            int x = 10;
            if(args.length > 0) {
                    x = Integer.parseInt(args[0]);
            }
            Scanner in = new Scanner(System.in);
             TreeMap<String, Integer> t = new TreeMap<>();

             while(in.hasNext()) {
                     String k = in.next();   
                     Integer cur = t.get(k);
                     t.put(k, cur == null ? 1 : cur +1);
             }

             in.close();

            //Printing: iterate through two nested for loops, 

             int curmax = 0;
             String curstring = null;
             for(int i=0; i<x; i++){
                     for (java.util.Map.Entry<String, Integer> e : t.entrySet()) {
                             if(e.getValue() > curmax)
//if the value of e is bigger then the last maximum, set the maximum equal to the value. 
                                     curmax = e.getValue();
                                     curstring = e.getKey();
                     }

                     System.out.printf("%d %s\n", curmax, curstring);

   //Switched order of printing since that's what the example result does.
                         t.remove(curstring);
                        curmax =0;
                 }
        }
}
dhsmith
  • 250
  • 1
  • 2
  • 11

0 Answers0