HashMap自动按key值进行排序
今天在做项目的时候,发现HashMap有自动排序的功能,但是我传入的是一个List,
而且是一个已经排好序的List,所以…在转换成map时顺序被打乱了
code:
private static Map<Integer,String> translateMap(List<TestPojo> list){
Map<Integer,String> map = new HashMap<Integer,String>();
for(TestPojo t:list){
map.put(t.getKey(), t.getVal());
}
return map;
}
然后是主方法测试:
public static void main(String[] args){
List<TestPojo> list = new ArrayList<TestPojo>();
TestPojo tp1 = new TestPojo();
tp1.setKey(23);
tp1.setVal("test1");
list.add(tp1);
TestPojo tp2 = new TestPojo();
tp2.setKey(46);
tp2.setVal("test2");
list.add(tp2);
TestPojo tp3 = new TestPojo();
tp3.setKey(2);
tp3.setVal("test3");
list.add(tp3);
Map<Integer,String> hmap = translateMap(list);
Iterator<Entry<Integer, String>> it = hmap.entrySet().iterator();
while(it.hasNext()){
Entry<Integer, String> et = it.next();
System.out.println(et.getKey()+"===="+et.getValue());
}
}
这个结果就是
2====test3
23====test1
46====test2
----分割线----
23====test1
46====test2
2====test3
这两者相比就看得出,这与我排好的序列(分割线一下的),不相符…
有遇到同样问题有解决办法的么….请不吝赐教…
版权声明:本文为u012255076原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。