简体   繁体   中英

Sort of Nested Maps, JAVA, innerMap not change keys from OuterMap

I trying to Sort NestedMaps like

Map<Integer,Map<String,Integer>>

Integer,String,Integer: FirstKey is ID, innerKey is Name, innerValue is PHONE. I am doing this:

           Set<Entry<Integer,Map<String,Integer>>> set = add.entrySet();
           List<Entry<Integer,Map<String,Integer>>> list = new ArrayList<>(set);
           Set<Entry<String,Integer>> set2 = add2.entrySet();
           List<Entry<String,Integer>> list2 = new ArrayList<>(set2);
           Collections.reverse(list);
           Collections.reverse(list2);

and looping to see results, if I have first 3 inputs with ID, Name , Phone: and i have result:

id 3 - phone 2, name I2; id 2 - phone 1, name I; id 1 - phone 5, name P;

next sorting should have to be with Name, and depending on ID-should change, but it doesnt work.

and how i have to sort with Name to get result like this:

id 2 - phone 1, name I; id 3 - phone 2, name I2; id 1 - phone 5, name P;

First of all, if you don't use wrapper objects for the cases like yours which require complex and chained data structures, your code will really look messy. And you should give meaningful names to your wrapper data structures. It will make your code easier to read and understand.

For representing Map<Integer,Map<String,Integer>> , you can use 2 wrapper classes, the inner map will be Map<Wrapper1> where Wrapper1 denotes String , Integer combinations. And you can define an outer map as Map<Wrapper2> where Wrapper2 denotes Integer and Map<Wrapper1> pairs.

And for sorting out your data, use TreeMap . As long as you supply proper comparison logic for your Wrapper instances, your map will be automatically sorted with TreeMap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM