Sorting in HashMap

In one of the earlier messages one person from the forum replied to me regarding sorting Hashmap and he asked me to use HashTree, but I see hashtree not available in 1.4 version. So could somebody provide me a pointer to sort the hashmap contents please.
Similar information :
http://forum.java.sun.com/thread.jspa?threadID=551191&tstart=225

I suggested a TreeMap if you want to keep a Map sorted on the keys. If you want the values sorted the best is probably to load the Map values into an ArrayList and sort it.

Similar Messages

  • An easy way to sort a HashMap by Key?

    Hi everyone,
    Is there any way to sort a HashMap by the key value using API 1.3.1?
    Thanks.

    Try using a TreeMap implementation instead. It'll maintain the keys in sorted order, as long as they have a Comparable implementation to tell the data structure how to sort them.
    If you've written your code properly, it'll be an easy change:
    // instead of this
    // Map myData = new HashMap();
    // use this.
    Map myData = new TreeMap();As long as you've used the Map as the reference type it's easy to switch.

  • Sorting a HashMap containing Pair/tuple

    Hi. I am trying to sort a HashMap looking like this:
    Map<String,Pair<Double,Double>> For sorting it with the "key", all I needed to do was to make a TreeSet of it.
    But any hints on how I can sort it on both my pair.getFirst() and another sort for pair.getSecond()?

    Simplified and not compiled, just to give you a direction:
    Collection<Pair<Double, Double>> col = hm.values();
    List<Pair<Double, Double>> list = new ArrayList<Pair<Double, Double>>(col);
    Comparator<Pair<Double, Double>> comp1 = new PairComparator1();
    Collections.sort(list, comp1);
    Comparator<Pair<Double, Double>> comp2 = new PairComparator2();
    Collections.sort(list, comp2);Note that PairComparator1and PairComparator2 must implement Comparator<Pair> and you need to write these classes.
    1 would compare based on the first value, 2 on the second value.
    Check Comparator's javadoc.
    Edited by: baftos on Jan 15, 2013 1:39 PM
    Edited by: baftos on Jan 15, 2013 1:41 PM

  • How can i sort a hashmap so that it can have duplicates

    i need to sort a hashmap so that it can have duplicates.

    How would you obtain the correct value, though? Suppose I add the values "fido", "rover", "mandibles", "fluffy" against the key "dog": How would you retrieve "fido"?
    This goes against the grain of what a Map is for, what are you actually trying to do?

  • Sorting a hashmap with duplicate values

    How would i sort the hashmap values in ascending order with duplicated values. thanks.

    One cannot sort a Collection unless it is a List or implements one of the sorted interfaces. Retrieving the values, one would have to put all of them into a List prior to sorting.
    If you need an ordered map that is ordered by its values, you need a custom class or a TreeMap with a custom Comparator. Read the according tutorials on Collection and ordering.
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

  • Sorting a HashMap

    Hi everyone!
    I'd like to know witch is the best way to sort a hashmap
    Let's imagine we've got many people in a place, and this people can build aliances with other people. Every person have an ID (key in the hashmap) and an aliance (value). Does exist any method to sort by value?
    I'd like a method that ask me for an aliance and i'd like to return a sortedset of people.
    Thanks and sorry for my bad writting!!!!
    visca el Bar�a!!!

    You want to create a TreeMap, using value as a key.

  • Sort generic HashMap by key?

    I have different lists of employees assigned to different projects. This information is contained in a HashMap as shown. I want to sort by the key (project) and then display sorted key (project) and corresponding value (employee list). Any ideas?
    Map<Project, ArrayList<Employee>> myMap = new HashMap<Project, ArrayList<Employee>>();
    myMap.put(project3, employeeListA);
    myMap.put(project1, employeeListB);
    myMap.put(project2, employeeListC);

    Toni_P wrote:
    Thank you for your help. I do need to keep the HashMap as a starting point since it's a result of a deserialization.Is it possible to convert existing HashMap into a SortedMap?Ok, as you can see, it's important to list requirements for getting the right solution ;)
    As I have no knowledge about how you deserialize the map or how many elements you have, to me, there seem to be two ways to solve your problem:
    1. Keep the HashMap and employ a SortedSet (most probably a TreeSet) on the map's keySet, iterate that SortedSet and fetch the values from the orgininal Map.
    2. Transfer the original Map to a SortedMap (most probably a TreeMap) and "drop" the original Map.

  • Sorting a HashMap by value

    Hi all,
    I have a hashMap that I need to sort into descending order by value w/out losing its key.
    Example Hash:
    301 | 12
    302 | 48
    303 | 10
    304 | 20
    Desired Results:
    302 | 48
    304 | 20
    301 | 12
    303 | 20
    I have searched the forums and found some similar situations but nothing exactly like what I am trying to do.
    I started out w/ this:
    public void sort(HashMap hash)
    List sortedList= new ArrayList(hash.values());
    Collections.sort(sortedList);
    However I lose my key & the arraylist is sorted ascending...
    Any help would be appreciated!

    You might extract the entry set, convert that to an array and use the static sort method of java.util.Arrays that accepts a Comparator. Implement a Comparator that looks into the entries (which are instances of Map.Entry that contain both key and value) and compares the values for whatever sorting order you want to establish.
    You might then iterate over the sorted array and place the values back in a HashMap to regain access via keys. Or maybe you just store Integer instances there, giving the position of the corresponding entry in the array, from where you find the values or keys - whatever you need on each access.
    Or you place that HashMap and the array in a new class that maintains them, allows to trigger sorting when needed, and provides access via key or position (internally using the array or the map as needed).
    If that class should behave exactly like a map, i.e. implement java.util.Map and ALSO provides the usual iterators and keyset, valueset and entry-collection etc... with all its related behaviors, then beware: That's a major programming task!
    Look at the sources of java.util.HashMap if you need to do that. Else do not implement java.util.Map and just implement the functionality that you really need at that point.

  • Sorting HashMap based on values

    I need to sort a hashmap based on the values, but also need to keep the keys available for retrieving the values.
    Example:
    key value
    1 c
    2 a
    3 b
    Desired Result
    2 a
    3 b
    1 c
    Thanks for your help.

    You can do this by getting all the Map.ENTRY values in a HashMap object then using a custom Comparator object to sort them by value.
    like this:
    HashMap hashMap =  // your HashMap
    Set entrySet = hashMap.entrySet;
    /* Now add them into a list and use the Collections
    * class to sort them.
    ArrayList list = new ArrayList();
    list.addAll(entrySet);
    Collections.sort(list, yourSpecialComparator);Hope this helps.

  • Sort() function used in HashMap, ArrayList or Collections?

    I need some testing codes for similar function like sort() for HashMap, Arraylist or Collection objects.
    Thanks in advance for help!

    http://developer.java.sun.com/developer/TechTips/1998/tt0421.html#tip1
    take a look at this link

  • Sorting the values in the HashMap maintaing the key-value relationship

    Hi,
    I want to sort the HashMap based on the values. I have tried several other ways but the closest I can get is sort the values but have to loose the keys. I wanted to sort the collection based on the values but at the same time maintain the key-value relationship. Is there any way I can get this functionality either by using any collection API or by some other way?
    Thanks and appreciate your help....
    --coolers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I believe that Commons Collections from Jakarta has something like that.
    http://jakarta.apache.org/commons/collections/
    But I'm not sure.

  • Want to sort HashMap based on Values with duplicate values

    Hi. I have a requirement to sort the HashMap based on the values not on the keys. My HashMap contains the values which are duplicates. My program is some thing like this.
    Map m = new HashMap();
    m.put ("Gosling", new Integer(2000));
    m.put ("Joy", new Integer(2000));
    m.put ("Schwartz", new Integer(3000));
    m.put ("Bracha", new Integer(4000));
    m.put ("Gafter", new Integer(3000));
    still i need to sort HashMap based on the values. How can i do it. I want the output some like this.
    Gosling 2000
    joy 2000 (may be interchanged)
    Schwartz 3000
    Gafter 3000 (Same as above)
    Bracha 4000
    Thanks.

    I found syntactical problems with above mentioned code.
    Here is edited working version:
    * test sortMap
    public void testSortMap () {
         Map m = new HashMap();
         m.put ("IGGHHG", new Integer(232353453));
         m.put ("ASDF", new Integer(345555000));
         m.put ("DSF", new Integer(345555000));
         m.put ("XYZ", new Integer(45555555));
         m.put ("AAA", new Integer(0));
         ArrayList outputList = sortMap(m);
         int count = 0;
         count = outputList.size();
              while(count > 0) {
                   Map.Entry entry = (Map.Entry) outputList.get(--count);
                   System.out.print("Key:" + entry.getKey());
                   System.out.println("\tValue:" + entry.getValue());
    * This method will use Arrays.sort for sorting Map
    * @param map
    * @return outputList of Map.Entries
    public ArrayList sortMap(Map map) {
         ArrayList outputList = null;
         int count = 0;
         Set set = null;
         Map.Entry[] entries = null;
    //     Logic:
    //     get a set from Map
    //     Build a Map.Entry[] from set
    //     Sort the list using Arrays.sort
    // Add the sorted Map.Entries into arrayList and return
         set = (Set) map.entrySet();
         Iterator iterator = set.iterator();
         entries = new Map.Entry[set.size()];
         while(iterator.hasNext()) {
              entries[count++] = (Map.Entry) iterator.next();
    //     Sort the entries with your own comparator for the values:
         Arrays.sort(entries, new Comparator() {
         public int compareTo(Object lhs, Object rhs) {
         Map.Entry le = (Map.Entry)lhs;
         Map.Entry re = (Map.Entry)rhs;
         return ((Comparable)le.getValue()).compareTo((Comparable)re.getValue());
              public int compare(Object lhs, Object rhs) {
         Map.Entry le = (Map.Entry)lhs;
         Map.Entry re = (Map.Entry)rhs;
         return ((Comparable)le.getValue()).compareTo((Comparable)re.getValue());
              outputList = new ArrayList();
              for(int i = 0; i < entries.length; i++) {
                   outputList.add(entries);
         return outputList;
         }//End of sortMap

  • Sort by arbitrary value of object inside Map

    I have a HashMap full of user objects, let's say. I want to sort the user objects in different ways. So if the user object contains name, age, height, weight, etc., I need to sort on any one of those at runtime.
    I've seen some example in the forums for sorting a HashMap by value (involves creating a new structure, which is fine), but I guess I need to write a comparator that digs INTO the objects and compares based on properties INSIDE the object. Is this simple to do? Any elegant solution for this? I'm sure I could brute force hack this, but I wanted to use Colleciton and Comparator if at all possible.

    Example without any 3rd party libraries (but please do):import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class Test {
        // don't use this, use something like BeanUtils
        // this just serves as a quick example
        private static Object getProperty(Object bean, String propertyName) {
            Object property = null;
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo (bean.getClass ());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors ();
                for (PropertyDescriptor propertyDescriptor: propertyDescriptors) {
                    if (propertyDescriptor.getName ().equals (propertyName)) {
                        property = propertyDescriptor.getReadMethod ().invoke (bean);
                        break;
            } catch (Exception exception) {}
            return property;
        public static class PropertyComparator<T> implements Comparator<T> {
            private String propertyName;
            public PropertyComparator (String propertyName) {
                this.propertyName = propertyName;
            public int compare (T a, T b) {
                Object valueA = getProperty (a, propertyName);
                Object valueB = getProperty (b, propertyName);
                // yet again - quite dirty [and not production ready :)], since null isn't instanceof anything
                if (! (valueA instanceof Comparable) || ! (valueB instanceof Comparable)) {
                    throw new IllegalStateException ();
                return ((Comparable) valueA).compareTo (valueB);
        public static void main (String... parameters) {
            List<Person> queen = new ArrayList<Person> ();
            queen.add (new Person ("Freddie", "Mercury"));
            queen.add (new Person ("Brian", "May"));
            queen.add (new Person ("John", "Deacon"));
            queen.add (new Person ("Roger", "Taylor"));
            System.out.println (queen);
            Collections.sort (queen, new PropertyComparator<Person> ("firstName"));
            System.out.println (queen);
            Collections.sort (queen, new PropertyComparator<Person> ("lastName"));
            System.out.println (queen);       
        private static class Person {
            private String firstName;
            private String lastName;
            public Person (String firstName, String lastName) {
                this.firstName = firstName;
                this.lastName = lastName;
            public String getFirstName () {
                return firstName;
            public String getLastName () {
                return lastName;
            @Override
            public String toString () {
                return String.format ("%s %s", firstName, lastName);
    }(This sorts a list, not a map. I'm sure you'll be able to adapt it to your situation.)

  • Sorting a hash map

    I have a hashmap with strings as keys, and float values as values, like below:
    {"anne=0.23453, barry=1.254339,steven=0.12449... }
    what i want to do is sort this hashmap according to the float values, returning the highest float value first. What i am currently doing is, swapping the keys with the values, so that the floats are the keys, and sorting them with a hashmap:
                     Set set = map1.keySet(); 
                     Map invertedMap = new HashMap();
                     for(Object o : set)
                         float val = (Float)map1.get(o);
                         invertedMap.put(val, o);
                TreeMap sorted = new TreeMap(Collections.reverseOrder());
                sorted.putAll(map1);
                Set set1 = sorted.keySet();
                  Iterator it = set1.iterator();
                        while(it.hasNext()) {
                            Object o = it.next();
                            System.out.println( o + " " + map1.get(o));
            }The problem here is that in the hash tables there a few floats are the same value, ie henry=1.6743, and mary=1.6743
    so when i invert the hash table, making 1.6743 one of these is ignored. Can anbody think of a way i can do this?
    Id appreciate any help
    Thanks

    Thanks, ive stored the entrySet in a list. A little
    unsure how to go about writting comparator to sort
    them by value though. Would you be able to explain
    this in a little more detail, please?Write a class that implements java.util.Comparator. Thre's but one method to implement, that is
    public int compare(Object o1, Object o2);
    Expect the arguments to be keys in your map. Fetch the value for each key and compare the values. That should be a problem since, if I got it right, those are java.lang.Floats, which implement java.lang.Comparable, so you can simply return: value1.compareTo(value2).
    Take a minute or two to read the Javadoc of the Comparator's compare method.

  • Indexed Hashmap

    Hi I'm looking for a way to have some sort of HashMap which uses both keys and index.
    I am implementing an in-memory caching system which stores aproximetly 200 small images. Each image has a hashcode which should be unique for all practical purposes. When my program starts it will capture these images and add them to a collection of some sort until the limit of 200 is hit, at this point the oldest entries are removed.
    I also need to check if a newly captured image is the same as one in the collection, should this be the case I will simply "promote" the existing image to the top of the list thus keeping it from being removed as the 201st image in the collection.
    Does anybody have any suggestions as to how I can achieve this?

    See LinkedHashMap
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashMap.html
    This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.

Maybe you are looking for

  • ABAP /4 processor: SYNTAX_ERROR

    Hi experts, I am basis engineer and I noticed one job fails in only one particular app server with ABAP dump. ABAP runime errors: SYNTAX_ERROR but the same job run well on other application servers. When i check the dump it say What happened? The fol

  • Cannot start apps, all marked as trials.

    Cloud Client 2.0.0.74 on Mac OS 10.10.3 Since yesterday when I updated Lightroom CC I cannot start the apps from CC any more. Some are marked with "begin trial", some not. When I start any app an activation window appears but in the end (after long w

  • Next page on ACS Report = Page not found

    Hi, I have ACS Appliance Release 3.3(3) Build 11. Everything works fine, except in the TACACS+ Accounting and TACACS+ Administration, in the Report menu. When I try to click on the next page, it says "Page not found". The other reports work fine. Is

  • VAX and VAY

    HI experts, I know that this question has been asked many times before, but after going through many threads, i still have some questions regarding these two. As to my knowledge, VAX is used when we do not use Sales Order as cost object, and VAY is t

  • [BootCamp Driver] Can not find the driver 'Netwrok Controller' on iMac 21.5

    Dear All, I installed bootcamp driver on serveral iMac and it worked fine. Now we got the new iMac 21,5'' and when I run BootCamp 3.0, it install all driver excepted for Network Controller. If I go to 'Manage' and then 'Device Manager', I can see 'Ot