-3

I have one hashMap in java and want to sort based on one of the key value . my hashmap likes like below.

HashMap= < string, map <string,string> >

key="toUppercase" -> value={ key="column_positions" -> value="4,5" ,
                             key="rule_order" -> value="3" }
key="replace" -> value= { key= "column_positions"-> value= "1,2" ,
                          key= "rule_order"-> value= "1" }
key= "concat" -> value={key= "column_positions"-> value= "6,7"
                        key ="rule_order"-> value= "2" }

I want to sort the hashmap based on rule_order. could you please help me.

My expected Output for outer hasmap is:

HashMap= < string, map <string,string> >

key="replace" -> value= { key= "column_positions"-> value= "1,2" ,
                          key= "rule_order"-> value= "1" }
key= "concat" -> value={key= "column_positions"-> value= "6,7"
                        key ="rule_order"-> value= "2" }
key="toUppercase" -> value={ key="column_positions" -> value="4,5" ,
                             key="rule_order" -> value="3" }

Thanks.

  • 2
    A `HashMap` doesn't have an order. You need to use a list or a `SortedMap`. – marstran Jan 02 '19 at 15:23
  • Look at a tree map. https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html You can provide a comparator or use the natural ordering of keys. – Nick Clark Jan 02 '19 at 15:43

1 Answers1

0

you can't sort by the key of the inner map. Moreover, you are not able to sort HashMap. You can use TreeMap but with ruleOrder as key. but in this case, you won't be able to store duplicates. (with same rule order). You can sort map in runtime :

Map<String, Map<String, String>> map = new HashMap<>();
 map.entrySet()
     .stream()
     .sorted(Comparator.comparing(en -> en.getValue().get("rule_order")))
     .forEach(this::doWork);

Please replce this::doWork with neaded code. Please pay attention that this sample is not null-safe.