码迷,mamicode.com
首页 > 编程语言 > 详细

遍历Map的两种方法(有排序)

时间:2016-04-05 09:21:15      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

初始化一个map

1
2
3
4
5
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、第一种方式,普遍使用

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

 2、第二种方式,容量大时推荐使用

1
2
3
4
5
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值排序

首先写个排序类

1
2
3
4
5
6
7
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里边才可以使用

1
2
3
4
5
6
7
8
9
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值排序

1
2
3
4
5
6
7
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());
    }
}

 排序输出

1
2
3
4
5
6
7
8
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: 如有错误请指出,我会及时修改

遍历Map的两种方法(有排序)

标签:

原文地址:http://www.cnblogs.com/shouce/p/5353685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!