Sorting map by value

I need to sort a map by value, or just display its contents by value (in descending order). The value is an int. I'm using a treemap, but I'm guessing it's impossible to sort it by anything but the value...then again i'm not really sure.
I've tried so many things, but I'm not experienced with maps so I'm having trouble.
Thanks.

Here is a class I wrote which will return a list of map.entrys in the order your comparator requires. Unfortunately, there is no way to get a Map sorted by values, only keys.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class MapValueSorter {
     public static <K, V> List<Map.Entry<K, V>> sortValues(Map<K, V> unsorted, Comparator<V> c) {
          List<Map.Entry<K, V>> orderedList = new ArrayList<Map.Entry<K, V>>();
          Comparator<Map.Entry<K, V>> entryComparator = new MapEntryValueComparator<K, V>(c);
          for(Map.Entry<K, V> entry : unsorted.entrySet()) {
               int insert = Collections.binarySearch(orderedList, entry, entryComparator);
               if(insert<0)
                    insert = 1-insert;
               orderedList.add(insert, entry);
          return orderedList;
     public static class MapEntryValueComparator<K, V> implements Comparator<Map.Entry<K, V>> {
          private Comparator<V> valueComparator = null;
          public MapEntryValueComparator(Comparator<V> c) {
               valueComparator = c;
          public int compare(Map.Entry<K, V> entry1, Map.Entry<K, V> entry2) {
               return valueComparator.compare(entry1.getValue(), entry2.getValue());
}

Similar Messages

  • Sorting Map on values rather than keys

    Is it possible that I can have a Map which is sorted based on values rather than keys ?
    If not is there an alternative.
    Basically I have keys as strings and values as integers.
    The values keep incrementing and at the end I want to get the top 50 keys based on the values.

    Sorting a Map by values is not a good idea, I did something similar before, it doesn't support the design, but it is better in performance, which is implementing a custom class (name it Record) that contains two members: key and value, create a record and insert it into a SortedSet e.g. TreeSet.
    make sure to do the following:
    1. This custom class must implement Comparable and compares two values
    2. Override euqlas method and accept strings (check using instanceof) then compare it to the key so you can retrieve the records using the key (to let it work as a map)
    Now you have a sorted set with key,value pairs, use the add method to insert a new pair, use the remove to retrieve the desired object and the set is already sorted :)
    Regards
    Mohammed

  • Sort Map by Value

    Hello,
    I have the following map:
    Key Values
    "String1" 1
    "String2" 8
    "String3" 3
    "String4" 7
    "String5" 3
    "String6" 1
    As you can see all the KEY are unique STRINGS and the Values are non UNIQUE INTEGERS. I want to sort(descendent) this map BY VALUE.
    I have tried a lot of methods but I did not reach in a clear Result.
    Please help me by giving source code.
    I would also you to check if the following Comparator class is suitable for my problem
    class FrequencyComparator implements Comparator{
    public int compare(Object firstObject, Object secondObject){
    Map.Entry first = (Map.Entry)firstObject;
    Map.Entry second = (Map.Entry)firstObject;
    if (Integer.parseInt(first.getValue().toString()) < Integer.parseInt(second.getValue().toString()))
    return -1;
    if (Integer.parseInt(first.getValue().toString()) == Integer.parseInt(second.getValue().toString()))
    return 0;
    return 1;
    Thanks in advance

    Crossposted,
    http://forum.java.sun.com/thread.jsp?forum=31&thread=425045&tstart=0&trange=15

  • Map default values in Header based on multiple values in the line item

    Hi
    I have a scenario in which the Header field of an IDOC should be populated with some default values based on some mixed mvt types in the line items.
    eg:
    Header -
    > Delivery type -
    > needs to be mapped to A (for X of line item 1)or B (for Y of line item 2) or C (for Z of line item 3 )
    based on line items field
    line item1---> mvt type---> X
    line item 2-->mvt type----->Y
    line item 3 -
    > mvt type -
    > Z
    mvt types doesnt necessarily have to come in that order and even the same mvt type can repeat in multiple line items.
    Can we achieve this logic in XI ?

    I think if you include removeContext, Sort, SplitByValue (on Value Change), CollapseContext to mvt type in all line items and then use ifelse condition to achieve your result.
    I will give an example of line Item1
    mvt type --->RemoveContext ->Sort>SplitByValue(on value change) --> CollapseContext
    Use the above mapping to IF function and check if it is having X, Y or Z then map the appropriate value to target field.
    Do the same for rest of the line items.

  • Sorting Hashtable by value

    All,
    I have a Hashtable with key (String) and value(float) now I want to sort it by value without disturbing the key value match
    I know, it can be done by sorting the keys... and then calling get() to obtain the value for the key but I want exactly opposite..
    Thanks
    Vishal

    Set set = map.entrySet();
    Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
    Arrays.sort(entries, new Comparator() {
              public int compare(Object o1, Object o2) {
         Object v1 = ((Map.Entry) o1).getValue();
         Object v2 = ((Map.Entry) o2).getValue();
         return ((Comparable) v1).compareTo(v2);
    });And how would one genericise(?) the above code snippet?
    I have the following attempt but I continue to receive one unchecked warning.
    Set<Map.Entry<String, String>> set = map.entrySet();
    Map.Entry[] entries = set.toArray(new Map.Entry[set.size()]);
    Arrays.sort(entries, new Comparatorlt;Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
                String v1 = e1.getValue();
                String v2 = e2.getValue();
                return v1.compareTo(v2);
            });

  • How to sort  the arry value in ascending order

    I have a string array where i need to sort the below values in ascending order in the same format...can anyone give me clue on this?
    9.3
    3.1
    9.1
    19.1
    19
    9.4
    9.1.1
    the sorted order should be
    3.1
    9.1
    9.1.1
    9.3
    9.4
    19
    19.1

    You may have easier luck writing your own comparator for this. These are headings in a table of contents, right?
    Write a comparator that tokenizes a string on the '.' character, or use a StringBuffer to remove them, and then order the elements according to the combined numbers. Since alphanumeric would order this list as you want it anyway you could just order that way once the '.' are removed.
    In other words your comparator would do this in the "compare" method:
    public class MyComparator implements Comparator, java.io.Serializable {
    private static Comparator stringComparator = java.text.Collator.getInstance();
    ...constructor(s), your own private "instance" variable of type MyComparator, a getInstance() method of your own, yadda yadda...
    public int compare(Object item1, Object item2) {
    try {
    value1 = removePeriods((String)item1);
    value2 = removePeriods((String)item2);
    if (value1 == null) {
    return (value2 == null) ? 0 : (-1);
    return compare(value1, value2);
    } catch (ClassCastException cce) {
    System.err.println("Wrong Object Type, JackAss!");
    protected int compare(String str1, String str2) {
    return MyComparator.stringComparator.compare(str1, str2);
    private String removePeriods(String value) {
    StringBuffer sb = new StringBuffer(value);
    int decimalIndex = value.indexOf('.');
    while (decimalIndex != -1) {
    sb.delete(decimalIndex, (decimalIndex + 1));
    }

  • Mapping input values for a web service connection to a range of cells

    I've created a web service connection in Xcelsius data manager. My web service requires an array of integer as input parameter. How do I map input values for a web service connection to read from a range of cells in the spreadsheet, e.g. $A$2:$A$20, in similar way of mapping output values to write to a range of cells in the spreadsheet?
    For output values of the web service, I can specify to map the output values to write to a range of cells. However, it doesn't seem to work for reading the input values.
    I can map input values for each node to a single cell, e.g. $A$2, in the spreadsheet. However, when I set the "Read From" field to a range of cells, e.g. $A$2:$A$20, it only reads in the first value in the range.
    Is there any way that we can do this mapping for input values as we do for output values?
    Your assistance is very much appreciated.
    Regards,
    Van

    Van,
    There is a workaround for that...
    Example:
    My Webservice accepts input data range in a specific format with " :" symbol, i.e. 072008:082008
    Now what i do is
    A1 = 072008
    A2 = 082008
    A3 = CONCATENATE(A1,":",A2)
    so A3 = 072008:082008
    Now i map the input value in web service to cell A3
    P.S have 2 input box components and map it to cells A1 and A2, i.e you are giving users an  option to enter the range of values...then web service will capture the range and refreshes data with the range of values user entered.
    hope this helps..
    -Anil

  • How to map column value (in table cell)

    Hi,
    My table, say product, has 'status' field (varchar(1))
    status = 0 -- unavailable product
    status = 1 -- avaialble product
    I want to map this value into readable 'available/unavailable'
    (a combo box cell editor) when I manipulate table cell (insert/search/modify)
    and status field correctly mapped into '0', '1'.
    Thanks,
    Tuan

    repost

  • Query needed for sorting by time value

    Hi Folks
    We have table it consists two columns like below
    Job_name varchar2(50)
    Scheduled_time date
    The filed scheduled time keep date and time value like below
    25-Jul-2009 4:00:10 AM
    26-Jul-2009 4:00:01 PM
    27-Jul-2009 4:00:00 PM
    28-Jul-2009 4:05:00 PM
    01-Jul-2009 4:06:00 PM
    02-Jun-2009 4:15:40 AM
    We need output as sorting by time value NOT date value. Expected output to be below
    25-Jul-2009 4:00:10 AM
    02-Jun-2009 4:15:40 AM
    27-Jul-2009 4:00:00 PM
    26-Jul-2009 4:00:01 PM
    28-Jul-2009 4:05:00 PM
    01-Jul-2009 4:06:00 PM
    I am using oracle 10G
    Thanks in Advance

    Here's how :
    SQL> create table job_table (job_name varchar2(50) not null, scheduled_time date);
    Table created.
    SQL> insert into job_table
      2  values ('Job_abc',to_date('25-JUL-2009 04:00:00','DD-MON-YYYY HH24:MI:SS'));
    1 row created.
    SQL> insert into job_table
      2  values ('Job_fdw',to_date('02-JUN-2009 04:15:40','DD-MON-YYYY HH24:MI:SS'));
    1 row created.
    SQL> insert into job_table
      2  values ('Job_fxj',to_date('27-JUL-2009 03:59:00','DD-MON-YYYY HH24:MI:SS'));
    1 row created.
    SQL> insert into job_table
      2  values ('Job_rjt',to_date('20-JUL-2009 14:59:00','DD-MON-YYYY HH24:MI:SS'));
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> alter session set nls_date_format='DD-MON-YYYY HH:MI:SS AM';
    Session altered.
    SQL> select job_name, scheduled_time from job_table
      2  order by to_char(scheduled_time,'HH24:MI:SS');
    JOB_NAME                                           SCHEDULED_TIME
    Job_fxj                                            27-JUL-2009 03:59:00 AM
    Job_abc                                            25-JUL-2009 04:00:00 AM
    Job_fdw                                            02-JUN-2009 04:15:40 AM
    Job_rjt                                            20-JUL-2009 02:59:00 PM
    SQL>

  • Mapping Item value Default and incrementing it

    Hi all
    I am new to sap XI, i am doing  a file to idoc scenario,
    how to map default value( for eg 0001) to an item field and keep on incrementing it by the occurence of no items in my file structure?
    Full points are guaranteed .
    Regards
    Bhasker.

    Hi,
    Any default value can be mapped by using the constants in the graphical mapping.
    Is your requirement is to count the no of occurance of a field i.e. item and map it to the target field..?
    If so use this mapping..
    items(Source) -
    remove contexts(node function) -
    count (Statistic function) -
    item field(target)
    Thanks
    SaNv...
    Edited by: Sãnthosh Kûmãr  V on Jul 30, 2008 10:25 AM

  • Can we apply sorting on Column values in Cross tab??

    Can we apply sorting on Column values in Cross tab??
    Following is the scenario with me.
    I have 2 fields and one formula.
    Fields are HostName and Username.
    Formula is status which categorizes the Authorized and Unauthorized events.
    And in the Summary Field, I am calculating the total number of events.
    In cross tab, Fields are marking the Rows of the cross tab and Formula is making the Columns(Authorized and Unauthorized ) of the cross tab.
    Since in cross tab data is grouped from left to right and sorted by default. I want to remove this default sorting and want to put sorting on the formula for Unauthorized events.
    Is there any way to fulfill this requirement?

    Hi,
    You can assign a number to each Unauthorised field e.g
    Rank   Unauthorised
    1         A
    2         BC
    3         DF
    5         TD
    6         GF
    Then add "Rank" to the crostab Columns before the Unauthorised  field. Then you can control the sorting order on your crosstab.
    Hope this helps
    Regards
    Dotun

  • How we can sort subtotal results value in abap alv report

    Hi, How we can sort subtotal results value in abap alv report

    Thanks a lot for your code
    but i am still getting double and weird results.
    Subtotal     IN     PARTY              KGS        TOTAL VALUE
         1     40008     3,141.20     192,799.00
         1     40008     16,681.06     1,908,659.00
    Subtotal     1          19,822.25     2,101,458.00
         10     40022     4,590.60     531,228.00
         10     40022     3,448.27     377,173.00
    Subtotal     10          8,038.87     908,401.00
         100     40010     270.172     19,852.00
    Subtotal     100          270.172     19,852.00
         101     40036     752.898     61,051.00
         101     40036     207.586     19,431.00
    Subtotal     101          960.484     80,482.00
         102     40048     325.936     32,154.00
         102     40048     264.32     19,364.00
    Subtotal     102          590.256     51,518.00
         103     40066     216.134     18,088.00
    Subtotal     103          216.134     18,088.00
         104     40001     231.96     16,986.00
    Subtotal     104          231.96     16,986.00
         105     40021     585.918     65,461.00
         105     40021     108.683     15,825.00
    Subtotal     105          694.601     81,286.00
         106     40046     209.777     15,341.00
    Subtotal     106          209.777     15,341.00
         107     40043     167.353     14,755.00
    Subtotal     107          167.353     14,755.00
         108     40046     153.023     14,343.00
         108     40046     342.348     32,223.00
    Subtotal     108          495.371     46,566.00
         109     40008     184.085     13,483.00
    Subtotal     109          184.085     13,483.00
         11     40011     5,275.63     524,232.69
         11     40011     6,723.28     643,911.82
    Subtotal     11          11,998.90     1,168,144.51
         110     40067     142.113     13,333.00
         110     40067     492.883     44,428.00
    Subtotal     110          634.996     57,761.00
         111     40040     118.961     13,190.00
         111     40040     492.433     60,029.00
    Subtotal     111          611.394     73,219.00
    Edited by: Timaji Sawant on Feb 16, 2012 12:16 PM
    Edited by: Timaji Sawant on Feb 17, 2012 9:27 AM

  • Sorting of Characteristics Values

    Hi Experts,
    I have one issue.When i am giving the values to the characteristic (Data format is CHAR)in the equipment (after assigned the class to the equipment)it is sorting the values example-1,10,3,5 even if I give 1,3,5,10.The requirement is it should be like 1,3,5,10 (as we input).Because of the CHAR format the system is sorting the values like this.If it is NUM format it is showing 1,3,5,10.
    Is there any way to stop the sorting of the values even if the data format is in CHAR?
    Regards
    Kalyan

    No.  For values there is no way to order them the way you want.  SAP sorts them.
    FF

  • Object map to value field

    Dear All,
    I know that
    KEI2 u2013 PA Transfer structure map to value field
    KE4I u2013 sd condition type to value field
    KE4R u2013 cost component to value field
    May I know if there is any other which map to value field?
    Thanks

    HI,
    We also have MM conditions.
    Kind regards
    umapathi g

  • Mapping the values of a Map as Transformation

    Hi,
    Is it possible to map the value of a (Java) Map with a transformation? The values in my Map are arbitrary object hierarchies, and I want to transform them to XML using XStream before they're put to a CLOB field in the database, and vice versa.
    Thanks!

    And I'm using 10g Release 3 (10.1.3)

Maybe you are looking for