• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 12943
  • Last Modified:

Sorting TreeMap by values Part 2

I founding an existing question that I am interested in having the answer to , however the proposed solution appears to sort by the key and not by the value.  How do you go about sorting by the value?

Below is the question/solution I am referencing.

 Solution Title: Sorting TreeMap by values
asked by durban_posion on 02/23/2003 08:17AM PST  
This solution was worth  50 Points and received a grade of A  
 


Hi there,
How do I sort TreeMap by integer values?

TreeMap example:

           Map map = new TreeMap(comp);
           map.put("1", "1000");
           map.put("6", "4000");
           map.put("8", "3000");
           map.put("25", "10000");
           map.put("13", "5000");
           map.put("19", "6000");

Result should be:

key             value
1               1000
8               3000
6               4000
13              5000
19              6000
25             10000  

Thanks DP
 

 
 Send to a Friend     Printer Friendly   See Solution  
   
 Comment from CEHJ
Date: 02/23/2003 08:19AM PST
 Comment  


It's already sorted by that value
 
Comment from durban_posion
Date: 02/23/2003 08:32AM PST
 Author Comment  


It is not

if u iterate this map result will be sorted by keys, not values.

1               1000
6               4000
8               3000
13              5000
19              6000
25             10000  

What I need is something that sotrs this map by values (1000,3000,4000, etc)

But thanks anyway for quick respond
 
Comment from CEHJ
Date: 02/23/2003 08:50AM PST
 Comment  


Oh, i thought you meant by the integer key.

    TreeSet ts = new TreeSet(new ValSorter());
    ts.addAll(map.values());

..............

class ValSorter implements Comparator {
  public int compare(Object o1, Object o2) {
    return new Integer((String)o1).compareTo(new Integer((String)o2));
  }
}

 
Comment from CEHJ
Date: 02/23/2003 08:51AM PST
 Comment  


You can print the set by:

System.out.println(ts);
 
Comment from durban_posion
Date: 02/23/2003 09:07AM PST
 Author Comment  


I also need keys.
Map must be sorted by values but must contain a key/value pair not just value as in your example.

Result should be:
key             value
1               1000
8               3000
6               4000
13              5000
19              6000
25             10000  

Thanks
 
Accepted Answer from CEHJ
Date: 02/23/2003 09:18AM PST
Grade: A
 Accepted Answer  


You have two alternatives - don't use Strings as keys as you've done or create the map using the class i gave you:

Map map = new java.util.TreeMap(new ValSorter());

 
Comment from CleanupPing
Date: 08/03/2003 03:00AM PDT
 Comment  


durban_posion:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
 
Administrative Comment from AnnieMod
Date: 11/12/2003 04:00AM PST
 Administrative Comment  


Force accepted

AnnieMod
Community Support Moderator @ Experts-Exchange
 

 
 
   
 
0
johngamble
Asked:
johngamble
  • 2
2 Solutions
 
aozarovCommented:
ArrayList list = new ArrayList(map.values());
Collections.sort(list); // or Collections.sort(list, <provide_your_comparator_if_values_are_not_comparable>);
0
 
CEHJCommented:
You can also reverse the map while sorting it by value if you want. Be aware of the implication of the uniqueness of keys though:

                  Map map = new TreeMap();
                  map.put("1", "1000");
                  map.put("6", "4000");
                  map.put("8", "3000");
                  map.put("25", "10000");
                  map.put("13", "5000");
                  map.put("19", "6000");
                  
                  Map reverseMap = new TreeMap(new ValSorter());
                  Iterator iter = map.entrySet().iterator();
                  while (iter.hasNext()) {
                        Map.Entry e = (Map.Entry)iter.next();
                        reverseMap.put(e.getValue(), e.getKey());
                  }


      static class ValSorter implements Comparator {
            public int compare(Object o1, Object o2) {
                  return new Integer((String) o1).compareTo(new Integer((String) o2));
            }
      }
0
 
deltaninsCommented:
This might be overkill for you, but this is what I did:
I created an object of the key and value (well I didn't actually create the object, my key and value were actually in an object already), and put them in a set, for which I defined a Comparator which would sort them based on the value.
I then iterated around the set that I'd sorted and for the current oject in the iteration I extracted the key and value, and set them to a Map I'd created. An ordinary map will try to sort your keys based on their natural order, so to counteract this, I defined a Comparator for this Map, and overwrote the compareTo method to always return 1 (i.e. don't compare them at all, just give them back to me in the order I gave them to you)
This probably isn't the best way to do this, and if anyone else has other solutions I'd be interested in seeing them, but I hope this helps.
0
 
deltaninsCommented:
Actually, instead of using a Map (I was implying TreeMap here) and overwriting the compareTo method, you can use a LinkedHashMap because that preserves the order of insertion.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now