关于 HashMap 没有按照添加的顺序显示排序

2018 年 5 月 30 日 0 条评论 2.87k 次阅读 0 人点赞

一般来说HashMap的存取顺序是不一致的,比如说:

@Test
public void test(){
    HashMap<String, String>map=new HashMap<String, String>();
    map.put("1", "111");
    map.put("2", "122");
    map.put("3", "133");
    map.put("4", "144");
    map.put("5", "155");
    for(String str:map.keySet()){
        System.out.println("key is "+str+" value is "+map.get(str));
    }
}

输出的结果是:
key is 3 value is 133
key is 2 value is 122
key is 1 value is 111
key is 5 value is 155
key is 4 value is 144
也就是说不能保证取出数据的顺序和存入时一样,但是LinkedHashMap可以做到这点

LinkedHashMap<String, String>linkedHashMap=new LinkedHashMap<String, String>();
linkedHashMap.put("1", "111");
linkedHashMap.put("2", "222");
linkedHashMap.put("3", "333");
linkedHashMap.put("4", "444");
linkedHashMap.put("5", "555");
for(String str:linkedHashMap.keySet()){
    System.out.println("key is "+str+" value is "+linkedHashMap.get(str));
}

输出结果:
key is 1 value is 111
key is 2 value is 222
key is 3 value is 333
key is 4 value is 444
key is 5 value is 555

TreeMap也可以做到

    TreeMap<String, String>map=new TreeMap<String, String>();
    map.put("1", "1111");
    map.put("2", "2222");
    map.put("3", "3333");
    map.put("4", "4444");
    map.put("5", "5555");
    for(String str:map.keySet()){
        System.out.println("key is "+str+" value is "+map.get(str));
    }

输出结果
key is 1 value is 1111
key is 2 value is 2222
key is 3 value is 3333
key is 4 value is 4444
key is 5 value is 5555

雷雷

这个人太懒什么东西都没留下

文章评论(0)

(Spamcheck Enabled)