简体   繁体   English

嵌套地图,JAVA,innerMap的排序不会更改OuterMap的键

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

I trying to Sort NestedMaps like 我试图对NestedMaps进行排序

Map<Integer,Map<String,Integer>>

Integer,String,Integer: FirstKey is ID, innerKey is Name, innerValue is PHONE. Integer,String,Integer:FirstKey是ID,innerKey是Name,innerValue是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: 并循环查看结果,如果我的前3个输入的ID为ID,Name,Phone:并且我有结果:

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. 下一个排序必须与Name一起使用,并应根据ID进行更改,但这是行不通的。

and how i have to sort with Name to get result like this: 以及我必须如何与Name排序才能得到如下结果:

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. 为了表示Map<Integer,Map<String,Integer>> ,可以使用2个包装器类,内部映射将是Map<Wrapper1> ,其中Wrapper1表示StringInteger组合。 And you can define an outer map as Map<Wrapper2> where Wrapper2 denotes Integer and Map<Wrapper1> pairs. 您可以将外部映射定义为Map<Wrapper2> ,其中Wrapper2表示IntegerMap<Wrapper1>对。

And for sorting out your data, use TreeMap . 为了整理数据,请使用TreeMap As long as you supply proper comparison logic for your Wrapper instances, your map will be automatically sorted with TreeMap. 只要您为Wrapper实例提供适当的比较逻辑,您的地图就会使用TreeMap自动排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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