Map集合的排序和遍历总结

注意:

1.Map的排序只写了按照Key排序的。

2.Map的四种遍历,前三种遍历了Key和Value,后一种只遍历Value。

package com.onlinetest;


import java.util.*;

/**
 * Map集合的排序和遍历
 */

public class HuaWeiTest11 {
    public static void main(String[] args) {
//        Map<String,String> map=new HashMap<>();
        Map<String,String> map=new TreeMap<>();
        map.put("cthree","NO3");
        map.put("btwo","NO2");
        map.put("aone","NO1");
        map.put("dfour","NO4");

        //对map按照key升序排序
        sortMapByKey(map,true);

//        1、新循环遍历key和value
        for(String key:map.keySet()){
            System.out.println("新循环遍历key和value:"+key+" "+map.get(key));
        }

//        2.迭代器历key和value
        Iterator<Map.Entry<String,String>> iterator=map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String,String> entry=iterator.next();
            System.out.println("迭代器遍历key和value:"+entry.getKey()+" "+entry.getValue());

        }

//        3.Entry遍历key和value
        for(Map.Entry<String,String> entry:map.entrySet()){
            System.out.println("Entry遍历key和value:"+entry.getKey()+" "+entry.getValue());
        }

//        4.遍历value
        for(String value:map.values()){
            System.out.println(value);
        }





    }
    public static Map<String, String> sortMapByKey(Map<String, String> map, final boolean isRise) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if (isRise) {
                    // 升序
                    return s1.compareTo(s2);
                } else {
                    // 降序
                    return s2.compareTo(s1);
                }
            }
        });
        sortMap.putAll(map);
        return sortMap;
    }
}
输出:
新循环遍历key和value:aone NO1
新循环遍历key和value:btwo NO2
新循环遍历key和value:cthree NO3
新循环遍历key和value:dfour NO4
迭代器遍历key和value:aone NO1
迭代器遍历key和value:btwo NO2
迭代器遍历key和value:cthree NO3
迭代器遍历key和value:dfour NO4
Entry遍历key和value:aone NO1
Entry遍历key和value:btwo NO2
Entry遍历key和value:cthree NO3
Entry遍历key和value:dfour NO4
NO1
NO2
NO3
NO4

猜你喜欢

转载自blog.csdn.net/Colin_Qichao/article/details/81393890
今日推荐