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 789895
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T21:35:50+00:00 2026-05-14T21:35:50+00:00

I want to write a comparator that will let me sort a TreeMap by

  • 0

I want to write a comparator that will let me sort a TreeMap by value instead of the default natural ordering.

I tried something like this, but can’t find out what went wrong:

import java.util.*;

class treeMap {
    public static void main(String[] args) {
        System.out.println("the main");
        byValue cmp = new byValue();
        Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
        map.put("de",10);
        map.put("ab", 20);
        map.put("a",5);

        for (Map.Entry<String,Integer> pair: map.entrySet()) {
            System.out.println(pair.getKey()+":"+pair.getValue());
        }
    }
}

class byValue implements Comparator<Map.Entry<String,Integer>> {
    public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
        if (e1.getValue() < e2.getValue()){
            return 1;
        } else if (e1.getValue() == e2.getValue()) {
            return 0;
        } else {
            return -1;
        }
    }
}

I guess what am I asking is: Can I get a Map.Entry passed to the comparator?

  • 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-05-14T21:35:51+00:00Added an answer on May 14, 2026 at 9:35 pm

    You can’t have the TreeMap itself sort on the values, since that defies the SortedMap specification:

    A Map that further provides a total ordering on its keys.

    However, using an external collection, you can always sort Map.entrySet() however you wish, either by keys, values, or even a combination(!!) of the two.

    Here’s a generic method that returns a SortedSet of Map.Entry, given a Map whose values are Comparable:

    static <K,V extends Comparable<? super V>>
    SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1;
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }
    

    Now you can do the following:

        Map<String,Integer> map = new TreeMap<String,Integer>();
        map.put("A", 3);
        map.put("B", 2);
        map.put("C", 1);   
    
        System.out.println(map);
        // prints "{A=3, B=2, C=1}"
        System.out.println(entriesSortedByValues(map));
        // prints "[C=1, B=2, A=3]"
    

    Note that funky stuff will happen if you try to modify either the SortedSet itself, or the Map.Entry within, because this is no longer a “view” of the original map like entrySet() is.

    Generally speaking, the need to sort a map’s entries by its values is atypical.


    Note on == for Integer

    Your original comparator compares Integer using ==. This is almost always wrong, since == with Integer operands is a reference equality, not value equality.

        System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!
    

    Related questions

    • When comparing two Integers in Java does auto-unboxing occur? (NO!!!)
    • Is it guaranteed that new Integer(i) == i in Java? (YES!!!)
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want write a query to get the last 24 hours worth of job
I have sql select for which I want write criteria. I was googling some
I have List (Of Report). Report has 90 properties. I dont want write them
I'm working with a library (TreeView in Gtk to be specific) that allows you
The OpenSSL library allows to read from an underlying socket with SSL_read and write
My problem is this; I have to order a table of data. Each row
i have a table array dynamically generated from a data query and stored in
I'm rather new to both Java programming and to Android development, so my learning
i have table consist of columns : id,name,job and i have row stored with
void clearscreen ( void ) { char a = 'a' ; fflush ( stdout

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.