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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T23:49:59+00:00 2026-05-25T23:49:59+00:00

I want to sort a Java TreeMap based on some attribute of value. To

  • 0

I want to sort a Java TreeMap based on some attribute of value. To be specific, I want to sort a TreeMap<Integer, Hashset<Integer>> based on the size of Hashset<Integer>. To achieve this, I have done the following:

A Comparator class:

private static class ValueComparer implements Comparator<Integer> {
    private Map<Integer, HashSet<Integer>>  map = null;
    public ValueComparer (Map<Integer, HashSet<Integer>> map){
        super();
        this.map = map;
    }

@Override
    public int compare(Integer o1, Integer o2) {
        HashSet<Integer> h1 = map.get(o1);
        HashSet<Integer> h2 = map.get(o2);

        int compare = h2.size().compareTo(h1.size());

        if (compare == 0 && o1!=o2){
            return -1;
        }
        else {
            return compare;
        }
    }
}

A usage example:

TreeMap<Integer, HashSet<Integer>> originalMap = new TreeMap<Integer, HashSet<Integer>>();

//load keys and values into map

ValueComparer comp = new ValueComparer(originalMap);
TreeMap<Integer, HashSet<Integer>> sortedMap = new TreeMap<Integer, HashSet<Integer>>(comp);
sortedMap.putAll(originalMap);

The problem:

This doesn’t work when originalMap contains more than 2 values of the same size. For other cases, it works alright. When more than two values in the map are of same size, the third value in the new sorted-map is null and throws NullPointerException when I try to access it.

I can’t figure out what the problem is. Woule be nice if someone could point out.

Update:
Here’s an example that works when two values have the same size: http://ideone.com/iFD9c
In the above example, if you uncomment lines 52-54, this code will fail- that’s what my problem is.

  • 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-25T23:50:00+00:00Added an answer on May 25, 2026 at 11:50 pm

    Update: You cannot return -1 from ValueComparator just because you want to avoid duplicate keys to not be removed. Check the contract of Comparator.compare.


    When you pass a Comparator to TreeMap you compute a (“new”) place to put the entry. No (computed) key can exist more than once in a TreeMap.


    If you want to sort the orginalMap by size of the value you can do as follows:

    public static void main(String[] args) throws Exception {
    
        TreeMap<Integer, HashSet<Integer>> originalMap = 
            new TreeMap<Integer, HashSet<Integer>>();
    
        originalMap.put(0, new HashSet<Integer>() {{ add(6); add(7); }});
        originalMap.put(1, new HashSet<Integer>() {{ add(6); }});
        originalMap.put(2, new HashSet<Integer>() {{ add(9); add(8); }});
    
    
        ArrayList<Map.Entry<Integer, HashSet<Integer>>> list = 
            new ArrayList<Map.Entry<Integer, HashSet<Integer>>>();
        list.addAll(originalMap.entrySet());
    
        Collections.sort(list, new Comparator<Map.Entry<Integer,HashSet<Integer>>>(){
            public int compare(Map.Entry<Integer, HashSet<Integer>> o1,
                               Map.Entry<Integer, HashSet<Integer>> o2) {
    
                Integer size1 = (Integer) o1.getValue().size();
                Integer size2 = (Integer) o2.getValue().size();
                return size2.compareTo(size1);
            }
        });
    
        System.out.println(list);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to make a sort in Java. In my object I have many
i want to sort dictionary based upon value of each dictioanry item.but if i
I want to create a TreeMap in Java with a custom sort order. The
I have a 2D-array that I want to sort based on the second column.
I have a List of Java objects that I want to sort according to
I have a list of java beans, now I want to sort them with
I have Java bean class and I want to sort list of these beans
Say I want to create a sort of Pre-processor for existing java code, so
I want to sort array A based on values in Array B actually in
I want to sort results set first based on one column and then based

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.