简体   繁体   English

排序图<String, Object[]>

[英]Sort Map<String, Object[]>

I've created user defined Map ie 我已经创建了用户定义的地图,即

Map<String, Object[]> pass = new TreeMap<String, Object[]>();

Here I'm adding data to it inside for loop as shown below. 在这里,我在for循环中向其中添加数据,如下所示。

int row = 0;

 row++; 
 pass.put(row + "", new Object[] {"Data 1 : ","A"});
 row++;
 pass.put(row + "", new Object[] {"Data 2:", "B"});
 row++;
 pass.put(row + "", new Object[] {"Data 3:", "C"});
 row++;
 pass.put(row + "", new Object[] {"Data 4:", "D"});

But this data is not same as added order. 但是此数据与添加的顺序不同。 Map is storing these data in random order. 地图正在以随机顺序存储这些数据。 But I want these data in order. 但是我希望这些数据按顺序排列。 What needs to be done? 需要做什么?

The TreeMap will sort your keys in their natural order (unless you inject a specific Comparator in its constructor). TreeMap将按其自然顺序对键进行排序(除非您在其构造函数中注入特定的Comparator )。

In this case, it will use the lexicographical order for String s. 在这种情况下,它将对String使用字典顺序。

Lexicographical order implies that: 词典顺序意味着:

  • 1 will come before 2 , but 12之前, 但是
  • 10 will come before 2 as well ! 10会前2 以及

If you need your keys to be sorted in numerical order, use Integer (or any Number ) for a key. 如果需要按数字顺序对键进行排序,请对键使用Integer (或任何Number )。

If instead, you need to retain the insertion order and don't care about sorting keys, you can use a LinkedHashMap . 如果相反,您需要保留插入顺序并且不关心排序键,则可以使用LinkedHashMap

As Keith points out, here 's the Java documentation for lexicographic String comparison. 正如Keith指出的那样, 是用于字典String比较的Java文档。

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

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