简体   繁体   English

如何对嵌套的哈希图进行排序?

[英]How to sort nested hashmaps?

The hashmap below forms like a table with key-value pair strings. 下面的hashmap图的形式类似于带有键值对字符串的表。 Integer represents row and column index respectively. Integer分别代表行索引和列索引。

HashMap<Integer,HashMap<Integer,HashMap<String,String>>> fullMap = new HashMap<Integer,HashMap<Integer,HashMap<String,String>>>();

How do I sort the innermost hashMap? 如何排序最里面的hashMap? sort row by keys ascending order 按键升序排列行

unsorted output: 未排序的输出:

.      0           1           2   
0  john,men     ace,his    hish,opt  
1  vrix,alt    home,jul     ics,ard  

sorted output: 排序输出:

.      0           1           2   
0   ace,his     john,men    hish,opt 
1  home,jul      ics,ard    vrix,alt 

I recommend you sort your maps on use rather than change the way the data is stored. 我建议您对使用的地图进行排序,而不要更改数据的存储方式。

If I understand your question, you wish to sort by the keys in the key-value pairs. 如果我理解您的问题,则希望按键值对中的键进行排序。 If that is correct, then you can do: 如果正确,则可以执行以下操作:

void processRow(Map<Integer,Map<String,String>> row) {
    row.entrySet().stream().sorted(Map.Entry.comparingByKey())
        .forEach(entry -> ...);
}

As an aside, your analogy of your data structure as a table is confusing. 顺便说一句,您将数据结构比作表的类比令人困惑。 It's a map from int to int to string to string. 这是从int到int到从字符串到字符串的映射。 This could represent a table where each cell is a list of key/value pairs. 这可以代表一个表格,其中每个单元格都是键/值对的列表。 But that's a pretty unusual table. 但这是一个非常不寻常的表。

A more conventional representation of a relational table would be something like List<Map<Column,Value>> . 关系表的更常规表示形式将类似于List<Map<Column,Value>>

Sorting of map entries based on keys can be achieved using TreeMap. 可以使用TreeMap基于键对地图项进行排序。 Create HashMap< Integer,TreeMap< String, String>> to maintain column format. 创建HashMap <Integer,TreeMap <String,String >>以维护列格式。

Map<Integer, Map<String,String>> map = new HashMap<>();
Map<String, String> treeMap1 = new TreeMap<>();
treeMap1.put("john","men");
treeMap1.put("ace","his");
treeMap1.put("hish", "opt");
Map<String, String> treeMap2 = new TreeMap<>();
treeMap2.put("vrix","alt");
treeMap2.put("home","jul");
treeMap2.put("ics", "ard");
map.put(1, treeMap1);
map.put(2, treeMap2);

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

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