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

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.

  • Convert hashmap (containing null values) to hashtable

    hi
    the following code gives me java.lang.NullPointerException
    how can i convert a hashmap ( contaiing null values ) to hashtable... ??
    and vice versa ?
              HashMap hm =new HashMap();
              hm.put("1","one");
              hm.put("2","two");
              hm.put("3","three");
              hm.put("4",null);
              Hashtable ht = new Hashtable(hm);how ever the code will run perfectly well if i remove
                   hm.put("4",null);Regards
    Lav

    so does that mean that theres is no way to convert a
    hashmap containing null values to hashtable ..!!There are several ways described above.
    If you mean is there a way to preserve the nulls as nulls, then, no, you cannot do that, because, as stated in the docs, null cannot be a key or value in a Hashtable.

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

  • 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 a vector of pairs in Solaris Studio 12.4 beta July refresh

    The following C++ program doesn't compile in C++11 mode with the Solaris Studio 12.4 beta July refresh compiler:
    #include <algorithm>
    #include <string>
    #include <utility>
    #include <vector>
    int main(int, char **)
        std::vector<std::pair<int, std::string>> vec;
        vec.emplace_back(1, "a");
        vec.emplace_back(3, "c");
        vec.emplace_back(2, "b");
        std::sort(vec.begin(), vec.end());
        return 0;
    Compiling with:
    % CC -std=c++11 Main.cc
    results in:
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/include/CC/gnu/bits/stl_pair.h", line 263: Error: The name __x is unusable in std::iter_swap<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 88:     Where: While instantiating "std::iter_swap<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>)".
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 88:     Where: Instantiated from std::__move_median_to_first<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 2282:     Where: Instantiated from std::__introsort_loop<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, int>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, int).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 5452:     Where: Instantiated from non-template code.
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/include/CC/gnu/bits/stl_pair.h", line 263: Error: The name __y is unusable in std::iter_swap<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 88:     Where: While instantiating "std::iter_swap<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>)".
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 88:     Where: Instantiated from std::__move_median_to_first<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 2282:     Where: Instantiated from std::__introsort_loop<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, int>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, int).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 5452:     Where: Instantiated from non-template code.
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 103: Error: A constant expression is required here.
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 88:     Where: While instantiating "std::iter_swap<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>)".
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 88:     Where: Instantiated from std::__move_median_to_first<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 2282:     Where: Instantiated from std::__introsort_loop<__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, int>(__gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, __gnu_cxx::__normal_iterator<std::pair<int, std::string>*, std::vector<std::pair<int, std::string> >>, int).
    "/opt/SolarisStudio12.4-beta_jul14-solaris-x86/lib/compilers/CC-gcc/include/c++/4.8.2/bits/stl_algo.h", line 5452:     Where: Instantiated from non-template code.
    3 Error(s) detected.

    Thanks for reporting this problem. I have filed bug 19325210 for you.

  • Sort on field containing Hebrew description in PowerView connected to MultiDimentional Model

    Hi,
    We are connected to MultiDimentional via Power View in SharePoint 2013.
    The Local Identifier Code is 1037 (Hebrew).
    The problem is that every time you check a field containing description in Hebrew
    the query is stuck, cause there is an automatic Order by clause on fetched fields
    in the query generated by the PowerView. For ex:
    EVALUATE
      FILTER(
        KEEPFILTERS(
          SUMMARIZE(
            VALUES('DW DIM CUSTOMERS'),
            'DW DIM CUSTOMERS'[BRANCH CD.Key0],
            'DW DIM CUSTOMERS'[BRANCH CD]
        NOT(ISBLANK('DW DIM CUSTOMERS'[BRANCH CD.Key0]))
    ORDER BY
      'DW DIM CUSTOMERS'[BRANCH CD], 'DW DIM CUSTOMERS'[BRANCH CD.Key0]
    If the order by on 'DW DIM CUSTOMERS'[BRANCH CD] (the desc of the branch)
    removed (manually in SSMS) the query runs without any performance issues.
    How this could be fixed?
    TY

    Hi Dimitri,
    According to your description, did you want to improve MDX query performance?
    In SQL Server, we can consider following conditions to improve SSAS query performance:
    Use calculated members with Scope assignments instead of using IIF.
    Remove empty tuples from MDX result.
    Optimize cube and measure group design, etc.
    Reference:
    http://technet.microsoft.com/en-gb/library/cc966527.aspx
    As per my understanding, there is no limit to the number of columns in the ORDER BY clause; however, the total size of the columns specified in an ORDER BY clause cannot exceed 8,060 bytes. It may be cause the similar issue.
    If there are any misunderstanding, please feel free to let me know.
    Regards,
    Alisa Tang
    Alisa Tang
    TechNet Community Support

  • Sorting a List containing Symbols?

    Hi,
    My problem relates to ordering results from a Hibernate query.
    I'm using Hibernate to return all records from a specific database table in the form of a List. The query contains an "order by" clause, and so my results look something like this (results ordered firstly alphanumerically, then alphabetically):
    1
    2
    9
    A
    B
    C
    Z
    The "problem" occurs when I retrieve records that contain symbols. I was hoping that such records would appear at the beginning of my retrieved records, and indeed that is the case for the majority of symbols, i.e.
    $
    1
    2
    9
    A
    B
    C
    Z
    However, for some reason, certain symbols are appearing at the END of my results. So my list of results looks something like this...
    $
    1
    2
    9
    A
    B
    C
    Z

    I assume that this ordering is the default one for Oracle.
    I want to sort my list of results so that ALL symbols appear at the beginning of the list. I was thinking about using some sort of Comparator, i.e.
    List result = Collections.sort(q.list(), new YourComparator());
    However, I'm not sure what code would go inside YourComparator() to compare symbols and order them accordingly. Perhaps comparing the ASCII codes might be an idea(?)
    Another solution might be to loop through each of my results and add the symbols and "non symbols" to separate lists, then order each list separately and combine them at the end. However this would probably have a major processing overhead.
    Any other (simpler) suggestions?
    Thanks in advance.

    If there are non-ASCII characters in your data, ASCII values probably won't do the job. If so, look at some of the static methods of the Character class. You should be able to build your own Comparator.

  • Query to sort a column containing alphanumeric values

    Hi,
    I have a table whose column contains ALPHANUMERIC values. The column is of type VARCHAR(1).
    I tried many queries (using UNION) to fetch records in Alphabets first and Numbers as last
    I.e. A-Z should come first and then 0-9 values.
    Please do the needful
    Regards,
    Mradul

    I.e. A-Z should come first and then 0-9 values.Edit: Whoops, I forgot the ascii values for numbers were lower.
    WITH t AS
    (SELECT '0' c FROM DUAL
      UNION
    SELECT '9' c FROM DUAL
      UNION
    SELECT 'A' c FROM DUAL
      UNION
    SELECT 'B' c FROM DUAL
    SELECT c
      FROM t
    ORDER BY TRANSLATE( UPPER(c)
                       , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
                       , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
         , TRANSLATE( UPPER(c)
                    , '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                    , '0123456789'
    C
    A
    B
    0
    9Message was edited by:
    vg

  • What am I doing wrong??? -- HashMap containing Sequences...

    I have the following code...
    var sprite:HashMap = new HashMap();
         var standingImage:Image = Image{ url:"sprite.jpg" };
         sprite.put("standing", [standingImage] as Image[]);
         var sp:Image[]= sprite.get("standing") as Image[];
    ... and throws an error
    java.lang.ClassCastException: com.sun.javafx.runtime.sequence.ObjectArraySequence cannot be cast to javafx.scene.image.Image
    I tried a few other things like
    var sprite:HashMap = new HashMap();
    var standingImage:Image[] = [Image{ url:"sprite.jpg" }];
         sprite.put("standing", standingImage );
         var sp:Image[]= sprite.get("standing") as Image[];
    and still get the same ClassCastException.
    How do I obtain an Image sequence from a HashMap?
    Thanks!
    Edited by: Molamini on Oct 16, 2009 8:17 PM
    Edited by: Molamini on Oct 16, 2009 8:18 PM

    It appears that the solution to this problem is to create a wrapper class that holds the sequence.
    For example
    public class ImageWrapper
    var images:Image[]
    def sprite:HashMap = new HashMap();
    var standingImage:Image[] = [Image{ url:"sprite.jpg" }];
    sprite.put("standing", ImageWrapper{ standingImage} );
    var sp= sprite.get("standing") as ImageWrapper;
    println("{sp.images}");
    If anyone knows a better solution than this, I'd like to know about it.

  • Array is sorted backwards, and contains unwanted fields?....

    Hi all
    I am creating an array from the flashVars passed from html.
    the string in the html flashVars params looks like this:
    var1=01.jpg|02.jpg|03.jpg&var2=01.jpg|02.jpg
    So basically each var is a list of images separated with the
    bar sign "|"
    I am succesfully retreiving the flashVars into an
    actionScript array, then I create a new array of
    the listed images, using the split function:
    for(var sVar in flashVars){
    var stringVal = flashVars[sVar];
    images = stringVal.split("|");
    Now, when I loop through the images array and output the
    result, I get these values, in this order:
    [type Function]
    03.jpg
    02.jpg
    01.jpg
    What is [type Function] and how did it get in my array?
    Then, why are the array values sorted in reverse order (last
    image is first, first image is last)?....
    I hope you can help.
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    An Ingenious WebSite Builder:
    http://sitelander.com

    hi
    var sVar:String =
    "01.jpg|02.jpg|03.jpg&var2=01.jpg|02.jpg";
    var my_array:Array = sVar.split("|");
    for (var i:Number = 0; i<=3; i++) {
    trace(my_array
    i hope that it'll help you

Maybe you are looking for

  • Graphic problems/errors with Mainstage 3 and MBP (15'' 2011)

    Hi, I bought Mainstage 3 for my MBP (15'' 2011). When i click con "perform" i get graphic errors. I have the same issue with the old Mainstage version since Mountain Lion. Also a fresh installation didn't help. I think i'm not the only one with this

  • How to make use of 32bit packages on Arch64

    Hello everyone, I recently installed arch 64bit which was not yet fully tweaked to suit my needs.  My 32bit version has some nice apps and I would like to know how to make use of them or even reuse them so that I won't download things anymore because

  • Incoming Payments Layout - Duplicated lines

    Hi all, I'm using 'Receipt(System)' template on SAP B1 2007A. This template has two tables, one that only shows up when we are paying in checks and the other one saying what documents are we paying. The problem is that in this table with the paid doc

  • Migration object for Aggregated Invoice

    Hi Experts, Just wanted to know if there is any object to migrate Aggregated Invoice in deregulated market scenario in a distributor's system which updates field DFKKTHI-BCBLN. We are able to migrate the open individual invoices of final customers as

  • I am unable to open my Iphone

    I am unable to open my iPhone 4. I am in truble plz help