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.

Similar Messages

  • 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

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

  • Sorting the list of value like in BEX but out of crystal report

    All,
    I have created a crystal report base on a BEX query where I have a variable for which  i am filtering base on a field period.fiscalyear.
    for the list of values that prompt you for this variable ...
    l in BEX we can do the sort by either alphabetical ascending order or descending alphabetical order such as:
    here is for ascending
    001.2008
    001.2009
    or by clicking on it we can do the following: (descending)
    012.2009
    012.2009
    however in crystal when refreshing the report in infoview it sorts the list of value base on the month
    something like this :
    JAN 2008 [0FISCPER].[K42008001]
    FEB 2008 [0FISCPER].[K42008002]
    We would like to have in crystal the same behaviour than in BEX,  so in crystal we would like to be able to get the list of values sorted in either ascending order to descending order. is there a way to do so ?
    notes also that we would like to avoid to create the variable in crystal
    Philippe

    Hi,
    in Crystal Reports you have per InfoObject - depending on the definition - the key value, the description and the member unique name. In BW these objects are defined as NUMC in most cases - which means it is a character / string.
    In your example the value is 001.2008 and 001.2009. What you can do in Crystal Reports is to split up the values into year and month and then sort based on the actual numbers.
    Ingo

  • How to access sort direction and filter value of columns?  Can I catch the 'filtered' or 'sorted' event?

    We have some columns being added to a table.  We have set the sortProperty and the filterProperty on each of our columns.
    This allows us to both filter and sort.
    We want to be able to access the columns filter value and sort value after the fact.  Can we access the table and then the columns and then a columns properties to find these two items?  How can I access the sort direction and filter value of columns?
    We would also like to store the filter value and the sort direction, and re-apply them to the grid if they have been set in the past.  How can we dynamically set the filter value and sort direction of a column?
    Can I catch or view the 'filtered' or 'sorted' event?  We would like to look at the event that occurs when someone sorts or filters a column.  Where can I see this event or where can i tie into it, without overwriting the base function?

    Hey everyone,
    Just wanted to share how I implemented this:
    Attach a sort event handler to table - statusReportTable.attachSort(SortEventHandler);
    In this event handler, grab the sort order and sorted column name then set cookies with this info
    function SortEventHandler(eventData)
        var sortOrder = eventData.mParameters.sortOrder;
        var columnName = eventData.mParameters.column.mProperties.sortProperty;
        SetCookie(sortDirectionCookieName, sortOrder, tenYears);
        SetCookie(sortedColumnCookieName, columnName, tenYears);
    Added sortProperty and filterProperty to each column definition:
    sortProperty: "ColName", filterProperty: "ColName",
    When i fill the grid with data, i check my cookies to see if a value exists, and if so we apply this sort:
    function FindAndSortColumnByName(columnName, sortDirection (true or false))
        var columns = sap.ui.getCore().byId('statusReportTable').getColumns();
        var columnCount = columns.length;
        for(var i = 0; i < columnCount; i ++)
            if(columns[i].mProperties.sortProperty == columnName)
                columns[i].sort(sortDirection);

  • Need help Sorting a Hashtable using values??

    I have a hastable whose keys are unique but values are not. The problem is that i have to sort the hashtable by values.

    You can't really sort a Hashtable by values, at least not directly. What you probably want is a way to be able to iterate through all the values contained in the Hashtable in a way that is consistent with some order defined on those values. An easy way to do this goes as follows:
    Map  m;   // let that be your Hashtable
    List  vals = new ArrayList(m.values());
    Collections.sort(vals);  // uses the values natural order OR
    Collections.sort(vals, my_comparator);  // uses the order defined by my_comparator
    // this will iterate in the order defined on the values
    Iterator  it = vals.iterator();
    while(it.hasNext()) {
      Object val = it.next();
    }

  • How to sort HashMap by values?

    ?

    You can create a TreeMap out of your HashMap using the values as the key. Just remember that the keys can not be duplicates.
    Bosun

  • Sort a treemap/hashmap by values

    I'm writing a really simple program that creates a treemap and writes it line by line to a text file. I want it to be ordered by the values asociated with the keys, not by the keys themselves.
    The map simply has strings for keys, the value with each one is the number of times that string appears in the input text file.
    I've looked at the constructor treemap(Comparator c), but didn't really see how I could use it. Is there a simple way to get the text file sorted by values, not the keys?
    Thanks!

    Do you really need a SortedMap to do this? Is there any point when you really need the data sorted by the String keys?
    Probably easier, once you have the collection of String/frequency pairs, just to dump that into a List and sort the List using a comparator that looks at the frequency primarily.

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

  • Non-Database Item Sort Using Multiple Block Values

    I need to sort the result set of a block based on a calculated item. I found several messages addressing this, however they all speak to using the columns from within the same block as input variables to the function used to calculate the non-database column value.
    My problem is that I need to use values from a different block as input variables. I have not found a way to use them since I need to use the full block.column syntax. Forms does not like this and always thows an error right at the period(.). I need to do this because the column names are the same in each block. the function compares the column values and changes the record instance background a different color based based on how many of the column pairs match. Each block is mutually exclusive from each other and doing a accurate join is not really possible.
    I tried renaming the block column name to something unique, however I get a variable not bound error when I try to use it in the order by function even though their values are in the top most block.
    For Example:
    First Block. Contains a list of cases that need to be worked because the automated process could not find a valid provider based on the values received. This list is created by a background process.
    Table: CASE_MAIN
    TIN
    CASE_ID
    FCLTY_CM
    MEDICARE_CM
    Unrelated Second Block (i.e., no join). It uses the TIN value in the first block to get a list of all of the providers for the TIN associated with the Case so that a person can assign the correct Provider to the case (A TIN has a provider and address associated with it). As a result there is no link to the results of this table and the CASE_ID. That's what the users needs to do manually
    Table: PROVIDER_MAIN
    FCLTY
    MEDICARE
    I need to take the values in the first block and compare them in the second block so that I can recolor the background based on matching logic in the function below.
    order by clause = get_vals( ''||:FCLTY_CM||''
    ,''||:MEDICARE_CM||''
    ,fclty
    ,medicare) desc
    I am able to do the coloring within the form easily, however I need to order them by how many values match exactly so the ones that match to most value pairs show at the top. Hence ordering by the result of the function. I return a 0,1, or 2 based on the matches. 0 for none and 2 for both.
    I cannot create a view because the sources of the information I need to compare are NOT related to each other, yet. that is what the application is designed to do. I have a case without a
    provider assigned, but I have a tax id number that possible identifies the provider. I use this TIN to query the provider table for all of the possible providers under that TIN. As a result there is no link between the case information and provider information. The goal is to get this list compare the values from the target information and put the most likely matches on top, with
    the ones with the most matches first. I can create a function many ways that takes in various parameters. For example Case ID and Provider Id and query the records in subselects
    individually like so;
    select count(*)
    from (select fclty, medicare from case_main where case_id p_case_id) cm
    ,(select fclty, medicare from provider_main where prv_id = p_prv_id) pm
    where cm.fclty = pm.fclty
    and cm.medicare = pm.medicare
    If the number is greater than zero I know I have a match with that provider and I can sort accoringly. I can also pass in the target information from case_main and the provider inforation from provider_main and then do an if/then statement for comparing. Then I can use this function to create a column value for each record and then use the same reference to the function in the order by clause to order by that value.
    The problem comes in trying to reference the case_id or target information from a different block than where the fucntion needs to be used. I get a variable bound not error message. What am I missing here. Why can I not reference a uniquely named block item as a input variable to a function in a different block? Does Forms first figure out what it needs to retrieve and then executes the SQL for each block in isolation, or does the first block's result set get retrieved, then the second, third, etc. Based on the message i am getting I would suspect the former since it appears their is no value in subsequent blocks. If so is there anyway around this? thanks.

    Don't quite understand your problem completely. But this might help. I sure hope your Provider_Main is a single-record block ...otherwise, how would you supply a list of values of FCLTY and MEDICARE to the function that does the sorting? Be awere, too, that the order-by is processed by the server, and NOT by Forms.
    Assuming it is a single-record block, you can put the values into parameters:
    :Parameter.Fclty := :Provider_Main.Fclty;
    :Parameter.Medicare := :Provider.Medicare;
    Execute_Query;
    And your order-by clause would be
    get_vals( ''||:FCLTY_CM||'',''||:MEDICARE_CM||'',
    :Parameter.Fclty,
    :Parameter.Medicare) desc
    By the way, the first line of your order-by looks strange. Shouldn't it be:
    get_vals( FCLTY_CM || ',' || MEDICARE_CM,
    or even better, get_vals should take in 4 parameters:
    get_vals(Fclty_cm, Medicare_cm, :parameter.Fclty, :parameter.Medicare)

  • Sorting photos by keyword - $ value

    I recently moved my data from a PC to a Mac.  I've got a series of photos of collectibles that had tags (which have converted over to keywords).  Each photo has two tags - one for price (e.g. $1, $1.5, $2, etc.) and one tag for year offered (05, 06, etc.) .... I'd like to sort by low to high $ value but don't seem to be able to do so successfully - any suggestions on the easiest way to accomplish this? ... Thanks in advance ....

    There isn't a way to do it. The 01 will always preceed the $1.
    You could use the Title Field for one or other - Item Offered 06 type of thing...
    Regards
    TD

Maybe you are looking for

  • Safari will not open for me. Keep quiting unexpectedly.

    I was on pinterest and clicked on a link that ended up closing out safari. Since then, I can't open Safari. It keeps saying Safari quits unexpectedly. I can't resolve the matter. Here's the error report: Process:           Safari [588] Path:         

  • Multiple conversations with one person

    I want to save a Messages conversation with someone, and start a new conversation with the same person. When I select the person from my Contacts to start the new conversation, I am returned to the old conversation. How can I start a completely new c

  • Sdo_filter fail when query against a spatial view in different schema

    We have a table with X,Y coordinates and would like to run spatial query against it. We do not want to change the table structure, so we opt to use a function based index. USER_SDO_GEOM_METADATA is updated and index is built. Then we created a view w

  • How to increase field size in Internal table

    Hi friends, I want to concatenate around 20 fields in one internal table field, i declared the destination filed as character, now i am able to get around 12 to 13 fileds only , how to increase the length of this field to include all fields ? or how

  • Burn to disk plug in installed but it does not appear under Photo, plug ins

    I installed my first plug in for a trial, Burn to Disk. I went through install process and at end it said plug in is installed. I then go to Aperture, Photo, edit with plug ins and do not find it. What am I missing? thanks