0

I'm trying find a structure similar to a LinkedHashMap that sorts it by its value. I'll need to be able to update the values. I'll be checking the order very often, so I need a solution that avoids sorting the Map every time.

something like this:

DynamicSortedMap<String,Integer> map = new DynamicSortedMap<String,Integer>();
map.put("key1",4);
map.put("key2",3);
map.put("key3",6);
System.out.println("Map: "+map);
map.update("key1",1);
System.out.println("Update:"+map);

Output:

Map: {key3=6, key1=4, key2=3}
Update: {key3=6, key2=3, key1=1}

Is there any stucture that allows this? If not, any ideas of how to do it?

Thanks for your help,

magodiez
  • 741
  • 2
  • 10
  • 23

3 Answers3

1

I think you are looking for something like TreeMap, which is sorted by key:

SortedMap<String, Integer> map = new TreeMap<String, Integer>(); 
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

Even though LinkedHashMap in fact could be a good base for this it's unfortunately very limited in manipulating the iteration order. I think with apache common-collections your better on.

Bernd Ebertz
  • 1,317
  • 8
  • 10
0
class SortValueMap extends HashMap<String,Integer>{

    @Override
    public Set<Entry<String,Integer>> entrySet() {
        List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(super.entrySet());
        Collections.sort(entries, new Comparator<Entry<String,Integer>>(){

            @Override
            public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }});
        return new LinkedHashSet<Entry<String,Integer>>(entries);
    }
 }
    ...
SortValueMap  map = new SortValueMap();
map.put("key1",4);
map.put("key2",3);
map.put("key3",6);
map.put("key4",1);
System.out.println("Map: "+map);
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130