This content has been marked as final. Show 5 replies
Simplified and not compiled, just to give you a direction:
Note that PairComparator1and PairComparator2 must implement Comparator<Pair> and you need to write these classes.
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);
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
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, ...
Hunter_wow wrote:There is no Map implementation that can be sorted by values. TreeMap, as you said, sorts by keys.
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.
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.