JAVA 中 Map的按顺序 PUT如何实现 ?

2025-02-25 06:23:37
推荐回答(3个)
回答1:

public class TestMapSort {

/**
*@param args
*/
public static void main(String[] args) {

TreeMap map = new TreeMap();
for(int i=0; i<10; i++) {

int s = (int)(Math.random()*10);

System.out.println(s); //打印随机产生的数据无序

map.put(s,s); //测试随机put10个数字

}

Collection col = map.keySet(); //从map里取键集合,这里应该是排序的

Iterator it = col.iterator(); //遍历

while(it.hasNext()) {

int key =Integer.parseInt(it.next().toString()); //强制转换为int

System.out.println(key); //打印键
System.out.println(map.get(key)); //打印键对应的值

}
}
}
按照楼上的建议重新写了一个 我没有在Structs里面测,对立面的标签用起来感觉不习惯,我打印测试了 可以实现排序的功能

import java.util.*;

public class TreeMapTest {

@SuppressWarnings("unchecked")
public static Map.Entry[] getSortedTreeMap(TreeMap treemap) {

Set set = treemap.entrySet();

Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
.size()]);

Arrays.sort(entries, new Comparator() {

public int compare(Object arg0, Object arg1) {
Object key1 = ((Map.Entry) arg0).getKey();
Object key2 = ((Map.Entry) arg1).getKey();
return ((Comparable) key1).compareTo(key2);
}
});

return entries;
}

public static void main(String[] args) {

TreeMap tb = new TreeMap();

tb.put("11", "aad");
tb.put("ss", "aaaa");
tb.put("bb", "aa");
tb.put("aaa", "aad");
tb.put("fff", "aad");

Map.Entry[] set = getSortedTreeMap(tb);//调用上面方法排序

for (int i = 0; i < set.length; i++) {

System.out.println(set[i].getKey().toString());

System.out.println(set[i].getValue().toString());

}
}
}

回答2:

再多用一个List li = new List();
for () {
value=获取value();
key=获取key();
li.add(key);
MyMap.put(key,value);
}

在遍历显示的时候,这样。从list中按顺序取key,然后在map中取值也是顺序来了
for (int i = 0; i < li.length; i++) {
key = li[i];
value = Mymap.get(key);
}

回答3:

用comparator实现,可以去查查comparator的资料~~