Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7957999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T04:21:08+00:00 2026-06-04T04:21:08+00:00

I am trying to find the three highest values in a TreeMap. I wrote

  • 0

I am trying to find the three highest values in a TreeMap. I wrote a code that is kind of doing it, but I would like to ask whether you can suggest a more efficient way.
Basically, I am saving each word of my text in a TreeMap along with the number of times it appears in the text. Then I am using a comparator to sort the values. Then I am iterating through the newly created Map until I reach the last three values, which are the highest values after the sorting and print them out. I am going to use large texts, so this is not a very good way.
Here is my code:

class Text{
    public static void main(String args[]) throws FileNotFoundException, IOException{
        final File textFile = new File("C://FileIO//cinderella.txt"); 
        final BufferedReader in = new BufferedReader(new FileReader(textFile));                               
        final TreeMap<String, Integer> frequencyMap = new TreeMap<String, Integer>(); 

        String currentLine; 
        while ((currentLine = in.readLine()) != null) {  
            currentLine = currentLine.toLowerCase();  
            final StringTokenizer parser = new StringTokenizer(currentLine, " \t\n\r\f.,;:!?'"); 
            while (parser.hasMoreTokens()) { 
                final String currentWord = parser.nextToken(); 
                Integer frequency = frequencyMap.get(currentWord); 
                if (frequency == null) { 
                    frequency = 0; 
                } 
                frequencyMap.put(currentWord, frequency + 1);
            } 
        }  

        System.out.println("This the unsorted Map: "+frequencyMap);

        Map sortedMap = sortByComparator(frequencyMap);
        int i = 0;
        int max=sortedMap.size();
        StringBuilder query= new StringBuilder();

        for (Iterator it = sortedMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String,Integer> entry = (Map.Entry<String,Integer>) it.next();
            i++;
            if(i<=max && i>=(max-2)){
                String key = entry.getKey();
                //System.out.println(key);
                query.append(key);
                query.append("+");
            }
        }
        System.out.println(query);
    }

    private static Map sortByComparator(TreeMap unsortMap) {
        List list = new LinkedList(unsortMap.entrySet());

        //sort list based on comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o1)).getValue())
                       .compareTo(((Map.Entry) (o2)).getValue());
            }
        });

        //put sorted list into map again
        Map sortedMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry)it.next();
            sortedMap.put(entry.getKey(), entry.getValue());

        }
        return  sortedMap;
    }   
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T04:21:09+00:00Added an answer on June 4, 2026 at 4:21 am

    I would count the frequencies with a hash map, and then loop over them all, selecting the top 3. You minimize comparisons this way, and never have to sort. Use the Selection Algorithm

    -edit, the wikipedia page details many different implementations of the selection algorithm. To be specific, just use a bounded priority queue, and set the size to 3. Dont get fancy and implement the queue as a heap or anything. just use an array.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to write a program that would find the minimum spanning tree. But
I am trying to find out if there are any relevant measurements that LoadRunner
I was trying to find a bandwidth profiler in flex like there used to
I'm trying to find eveything inside a div using regexp. I'm aware that there
I have noticed that there are strange requests to my website trying to find
I'm trying to find best free expert system, with the highest functionality. I know
I am trying to create a system which would be able to find users
I'm trying to find a way to treat enums generically but I can't find
I'm trying to find the most efficient way to do something and would appreciate
I'm trying to use regular expressions to find three or more of the same

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.