This discussion is archived
5 Replies Latest reply: Jan 16, 2013 12:50 AM by 978140 RSS

Sorting a HashMap containing Pair/tuple

978140 Newbie
Currently Being Moderated
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()?
  • 1. Re: Sorting a HashMap containing Pair/tuple
    baftos Expert
    Currently Being Moderated
    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
  • 2. Re: Sorting a HashMap containing Pair/tuple
    978140 Newbie
    Currently Being Moderated
    What I can see only a list of Pair gets sorted there. I would like the Map to be sorted according to the Pair values.
  • 3. Re: Sorting a HashMap containing Pair/tuple
    EJP Guru
    Currently Being Moderated
    You need to write the Comparator, as he said, but you need to write it according to your ordering requirements, which you haven't specified in enough detail. If the first pair is the major key: if they are different, the comparator needs to return that difference, otherwise the difference of the second pair. If the second pair is the major key, ...
  • 4. Re: Sorting a HashMap containing Pair/tuple
    Kayaman Guru
    Currently Being Moderated
    Hunter_wow wrote:
    What I can see only a list of Pair gets sorted there. I would like the Map to be sorted according to the Pair values.
    There is no Map implementation that can be sorted by values. TreeMap, as you said, sorts by keys.

    If you intend to have a SortedMap that sorts according to values, you'll need to implement one yourself. Another option is to create a TreeMap with the Pair<> as the key and a custom Comparator.
  • 5. Re: Sorting a HashMap containing Pair/tuple
    978140 Newbie
    Currently Being Moderated
    Walked around the hard part of the problem by converting my Map with Pair values to an matrix of type String[][] and sorted it like this:
    http://stackoverflow.com/questions/4907683/sort-a-two-dimensional-array-based-on-one-column

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points