2

if i have a map like this:

Map<Fruit, Double> multiMap = new HashMap<Fruit, Double>();

is there a way for me to sort on the Double values while still keeping the Double values linked to the corresponding Fruit object?

initially i was thinking of doing something like this:

public ArrayList<Double> sortAllValues() {
    ArrayList<Double> allEntries = new ArrayList<Double>();

    for (Entry<Fruit, Double> entry : multiMap.entrySet())
        allEntries.add(entry.getValue());
    }
return Collections.sort(allEntries);
}

but if i do this i lose the linkage between the Fruit and the Double value... any ideas?

Thanks in advance

Steve Kuo
  • 60,372
  • 75
  • 191
  • 253
BigBug
  • 6,293
  • 22
  • 81
  • 131

3 Answers3

2

consider the following:

class ValuedFruit implements Comparable<ValuedFruit> {
    private Fruit fruit;
    private double value;

    @Override
    public int compareTo(ValuedFruit o) {
        return (value < o.value) ? -1 : ((value > o.value) ? 1 : 0);
    }
}
List<ValuedFruit> fruits = new ArrayList<ValuedFruit>();
void sort(List<ValuedFruit> fruits){
    Collections.sort(fruits);
}
BlackJoker
  • 3,009
  • 1
  • 19
  • 26
  • 2
    The compareTo method could just contain `return Double.compare(this.value, o.value)`, which would have the bonus of not breaking the ordering if any value happens to be NaN. – VGR Mar 20 '13 at 12:40
1

It is not possible that you can maintain order of map entries(key,value) based on the value but it could possible based on key with TreeMap<k,v>.

TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

What you could possibly do that is update your code -

public ArrayList<Double> sortAllValues() {    
     return Collections.sort(multiMap.values());
}

It will stop unnecessary iteration.

Subhrajyoti Majumder
  • 39,719
  • 12
  • 74
  • 101
  • for some reason, your answer looks very odd + this sentence made no sense whatsoever to me. **There is no way where you can sort map entry(key,value) on based on value but based on value it is possible with TreeMap** – Rahul Mar 19 '13 at 15:44
  • http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java – Franklin Mar 19 '13 at 15:46
  • Thanks for commenting I have updated it – Subhrajyoti Majumder Mar 19 '13 at 15:53
1

You just have single double value associated with every Fruit object. If this is the case then sorting doesn't make any sense. If you have multiple double values associated with a single Fruit object then change the structure of your map to something like this :

Map<Fruit, Set<Double>> multiMap = new HashMap<Fruit, Set<Double>>();

You can use TreeSet, to keep the values sorted.

Ankur Shanbhag
  • 7,586
  • 2
  • 27
  • 38