遍曆Map的兩種方法(有排序),map兩種方法

來源:互聯網
上載者:User

遍曆Map的兩種方法(有排序),map兩種方法

初始化一個map

12345 Map<String, String> map = new HashMap<String, String>();map.put("1""hell");map.put("2""hello");map.put("3""hel");map.put("4""hello");

1、第一種方式,普遍使用

1234 Set<String> keySet = map.keySet();for (String key : keySet) {    System.out.println("key= " + key + " and value= " + map.get(key));}

 2、第二種方式,容量大時推薦使用

12345 Set<Map.Entry<String,String>> entySet =  map.entrySet();for (Map.Entry<String, String> entry : entySet) {    System.out.println("key= " + entry.getKey() + " and value= "            + entry.getValue());}

 實驗發現輸出的順序是亂的,排個序吧

1、按照key值排序

首先寫個排序類

1234567 private static class KeyComparator implements        Comparator<Map.Entry<String, String>> {    public int compare(Map.Entry<String, String> m,            Map.Entry<String, String> n) {        return m.getKey().compareTo(n.getKey());    }}

 把資料放在list裡邊才可以使用

123456789 List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();list.addAll(map.entrySet()); KeyComparator kc = new KeyComparator();Collections.sort(list, kc);for (Iterator<Map.Entry<String, String>> it = list.iterator(); it        .hasNext();) {    System.out.println(it.next());}

 2、按照Value值排序

1234567 private static class ValueComparator implements        Comparator<Map.Entry<String, String>> {    public int compare(Map.Entry<String, String> m,            Map.Entry<String, String> n) {        return m.getValue().compareTo(n.getValue());    }}

 排序輸出

12345678 list.clear();list.addAll(map.entrySet());ValueComparator vc = new ValueComparator();Collections.sort(list, vc);for (Iterator<Map.Entry<String, String>> it = list.iterator();    it.hasNext();) {    System.out.println(it.next());}

 

Tips: 如有錯誤請指出,我會及時修改

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.