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.

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 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.

  • 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

    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.

  • Hashmap in Hashmap as Key?

    Can anybofy let me know, what could be the possible disastrous outcome of keeping Hashmap in Hashmap as Key?
    Could it lead to inconsistent behaviour?
    If its not a good idea to use Hashmap as key in a Hashmap what other data structure we can use for the same?
    Thanks,
    Amit G.

    Hello Amit,
    I have a question - "Will the contents of the HashMap, which is the key to your second HashMap, change over a period of time.".
    See sample below -
    import java.util.HashMap;
    import java.util.Map;
    public class Foo {
         private Map<Map, String> mainMP = new HashMap<Map, String>();
         private Map<String, String> one = new HashMap<String, String>();
         public static void main(String[] args) {
              Foo f = new Foo();
         Foo() {
              mainMP.put(one, "SomeStr");
              String str = mainMP.get(one);
              System.out.println("First Time : " + str);
              one.put("hello", "where");
              str = mainMP.get(one);
              System.out.println("Second Time : " + str);
    }When you run the program the result will be -
    First Time : SomeStr
    Second Time : null
    The reason is that the hashCode for a Map object depends on its contents. So Map one will have a different hashCode when it is empty and another one when it has the String "hello". So if you add or remove any object from within a Map, the hashCode will change.
    Having a HashMap as a key (which changes over time) to another HashMap is a sure recipe for disaster.
    If you could tell the scenarion where you are using it, maybe I could suggest a different data structure.

  • Sort by BPM and key????

    Does anyone know if you can still sort by BPM or key for loops anymore? I try to find loops that are around the same BPM as my project so they don't get too distorted. Now I'm lost and can't seem to find it. All that comes up is file name, beats and favorite. I hope this wasn't removed for the sake of simplicity.

    Hi Ryan,
    I had a similar issue and tried repairing Permissions, and deleting GarageBand's preference files as per Hangtime's suggestion. Didn't work for me either. But it did appear that all my loops were there jut not with the ability to search by key/tempo.
    So I had another look at Garageband's preference setting and noticed that in the Loops preferences there is to Display Original Tempo & Key at the bottom of the Preferences. Ticked this and I can sort again. Not sure why it changed but back to how it was now...
    Regards
    Shakey

  • 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

  • How to make data sorted by default by key figure?

    hi experts,
    how to make data sorted by default by key figure?

    Hi ,
    Try to make the selections for the filter of the query..
    Check this link ..
    http://help.sap.com/saphelp_nw70/helpdata/en/f1/0a5625e09411d2acb90000e829fbfe/frameset.htm
    Regards,
    Shikha

  • Question about reading generic tables with keys

    Hello
    I'm wondering if it's possible to read a generic table with key statement:
    FIELD-SYMBOLS:
        <lv_key>         TYPE zconf_key,
        <lt_data_bi>     TYPE INDEX TABLE,
        <lt_data_ai>     TYPE INDEX TABLE,
        <ls_data_bi>     TYPE any,
        <ls_data_ai>     TYPE any.
    * create data types
      CREATE DATA lt_data_bi TYPE (ls_node-data_table_type).
      ASSIGN lt_data_bi->* TO <lt_data_bi>.
      CREATE DATA lt_data_ai TYPE (ls_node-data_table_type).
      ASSIGN lt_data_ai->* TO <lt_data_ai>.
    * do check
      LOOP AT <lt_data_ai> ASSIGNING <ls_data_ai>.
        ASSIGN COMPONENT 'KEY' OF STRUCTURE <ls_data_ai> TO <lv_key>.
        READ TABLE <lt_data_bi> WITH KEY key = <lv_key>
        ASSIGNING <ls_data_bi> BINARY SEARCH.
    I receive the message: "The specified type has no structure and therefore no component called KEY" in the read statement above.
    Does anyone has an idea what I can do here?
    Regards,
      Mathias

    Mathias Glockner wrote:
    >     READ TABLE <lt_data_bi> WITH KEY key = <lv_key>
    In your structure ls_data_bi there is no field called KEY . please check whether you have field KEY in structure
    a®s

  • 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.

  • Sort descending by a key figure?

    Hello,
    This question relates to our Top 10 Vendors query. The default version of the report sorts in ascending order for total invoice value. I can change this from the right click context menu to be in descending order, but I can not figure out how to make this the default setting. The properties in the query do not have an option to sort by this key figure in an ascending or descending fashion. Can anyone tell me how to sort by a key figure?
    Thanks very much,
    Bob

    You can make a descending sorting for your key figure using the condition TopPercent (Top%) and take the value 100. To sort ascending, use the BottomPercent (Bottom%) condition on your key figure.
    Then 100 % of the values of your key figure will be shown in a descending sorting by default in your query (without using a view).
    I used the feature in the newest BEx Query Designer (7.x) and it works fine, I don't know if it's available in the older version (3.x).
    Please assign points.
    Kind regards,
    Ben De Windt
    Belgium

  • Sorting Values and keeping Keys

    Hi,
    I was hoping someone might be able to help me. I would like to sort some key value pairs.
    I have the following data the key is a string and the value is an int.
    "John",26
    "George",25
    "Ian",33
    "Greg",25
    I would like to sort the names by age and output them e.g
    Greg George John Ian
    I have looked at this post using the TreeMap and TreeSet to sort based on values but this seems to only work for Strings. Another problem is that I think tree set needs unique values and in my case they're not unique.
    http://forum.java.sun.com/thread.jspa?threadID=634742&messageID=3688987
    I was wondering whether someone could help me sort out this problem
    Thanks in advance
    John

    You need to create an Object to encapsulate your data and then sort a collection of those objects. Something like this:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=598401

  • Sort generic XML document hierarchically ?

    Hi
    I need to sort entire xml alphabetically by node names.
    I.e. alphabetic sort by node names on first level, then alphabetic sort
    each node's children (second level), etc.
    The result will be same tree, but sorted alphabetically.
    I do not know names and structure beforehand, this is abstract XML document.
    Sorting can be applied either to text form , or DOM form (Document).
    Any Ideas ?
    Thanks !

    My idea would be to use the xsl:sort element ofXSLT.
    Thanks , but I can't figure out how to define such
    generic xsl:sort rule.
    All examples of this rule refers to tags by their
    name. And in my case tag name itself should be
    subject for sorting.Wouldn't that just be <xsl:sort select="name()">?
    In addition, this sorting should
    be performed on all levels of document , and depth is
    not known beforehand.So what? Put that in a template that's applied to every element. And make sure you call <xsl:apply-templates> in that template so it gets applied at all levels.

Maybe you are looking for

  • I click to open itunes on my macbook and it doesn't open - can't see anything but can play music through finder

    Itunes won't open at all on my Macbook but I can see all my music on Finder??

  • 2-Colorable Problem

    Hello. I hope I am not disturbing anyone by asking about this, but I have a homework assignment due relatively soon that involves determining whether a graph is 2-colorable or not. I am having problems figuring out how to prove a graph is or isn't 2-

  • Exporting a table to an excel pivot fails

    Hi all, i'm using Discoverer Plus 9.0.4.45 and Microsoft Excel 2000 9.0.2812. When i create a crosstab with page-detail items and export it to an excel pivot table, everything works well but if i try to export a page-detail table i can only see a sta

  • How do I backup a drive?

    I have a 160GB /dev/hda with:   /dev/hda1 = /boot (ext2)   /dev/hda2 = swap   /dev/hda3 = / (resiserfs) I have a 200GB with unimportant data at /mnt/data1 I have a 200GB backup drive at /mnt/data2 Is there an easy way to backup the data from the 160G

  • Financial Reporting Studio - Grid POV

    I have a report running from HFM (9.3.1.3.0.2176) using Financial Reporting Studio (9 9.3.1.0.0.0325) where I have restricted the Grid POV to 'Select members from a list' on Accounts. When I run the report as an HTML from within Reporting Studio or w