0


I am trying to sort a hashmap based on alphabetical value which itself is stored inside another Map.

The structure looks like: Map<String, HashMap<String, String>>

I want to sort this Map based on the value of the HashMap inside so all in all the full map will be sorted so as the HashMap based on the HashMap's value.

-- UPDATE:

For example if I have something like:

Map: abc Value: HashMap[EN, a]
Map: xyz Value: HashMap[DE, c]
Map: pqr Value: HashMap[PL, b]

then after sort it should be something like:

Map: abc Value: HashMap[EN, a]
Map: pqr Value: HashMap[PL, b]
Map: xyz Value: HashMap[DE, c]

How to proceed?

000
  • 26,951
  • 10
  • 71
  • 101
beerBear
  • 969
  • 2
  • 17
  • 41

1 Answers1

6

Sorting on the value may be a bad idea, because it would suppose that sort becomes incorrect if you change what's in the value map.

If you really want to sort according to the value, then you need to create another map:

final Map<String, Map<String, String>> map= new HashMap<>();

Map<String, String> map1 = new HashMap<>();
map1.put("EN", "a");
Map<String, String> map2 = new HashMap<>();
map2.put("DE", "c");
Map<String, String> map3 = new HashMap<>();
map3.put("PL", "b");

map.put("abc", map1);
map.put("xyz", map2);
map.put("pqr", map3);

TreeMap<String, Map<String, String>> sorted = new TreeMap<>(new Comparator<String>() {

    @Override public int compare(String s1, String s2) {
        String value1 =  map.get(s1).values().iterator().next();
        String value2 =  map.get(s2).values().iterator().next();

        return value1.compareTo(value2);
    }
});
sorted.putAll(map);

for(Map.Entry<String, Map<String, String>> e : sorted.entrySet()) {
    System.out.println(e.getKey());
}
jaudo
  • 2,022
  • 4
  • 28
  • 48
  • @j0d0 I didn't get you at all. We just need to return a Map which contains 'HashMap sorted by value'. The source Map won't get changed...well..at that point of time. – beerBear Oct 22 '15 at 07:14
  • You tell you want to sort you map according to the HashMap, right? What will happen if you change the value of one hashmap? Maybe you won't do this, but it's an example to explain why you should not sort according to the value. – jaudo Oct 22 '15 at 07:40
  • @j0d0 please see updated question for example. Alright I get your point but this could be solved if we do recursively twice right? or maybe another dataset which holds the sorted hashmaps? – beerBear Oct 22 '15 at 07:47
  • 1
    I added an example in my answer – jaudo Oct 22 '15 at 07:58