一天一点学Java

Java基础-Map

2018-05-18  本文已影响0人  Sandy_678f

Map的一些操作

package com.sandy.MapDemo;

import java.util.*;

public class MapDemo {

    public static void main(String[] args) {

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(1,14);
        map.put(2,14);
        map.put(9,7);
        map.put(4,10);
        map.put(5,41);
        map.put(5,45);
        map.put(8,40);
        map.put(6,29);
        map.put(null,91);
        map.put(10,null);


        /*
        遍历Map的方法
         */
        /*
        方法一:通过EntrySet获取
         */
        System.out.println("遍历Map集合Key值: ");
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println("key:"+entry.getKey()+"  value: "+entry.getValue());
        }

        /*
        方法二:通过Iterator遍历
         */
        System.out.println("遍历Map集合Key值: ");
        Iterator<Map.Entry<Integer, Integer>> iteratorEntry = map.entrySet().iterator();
        while(iteratorEntry.hasNext()){
            Map.Entry<Integer, Integer> entry = iteratorEntry.next();
            System.out.println("key:"+entry.getKey()+"  value: "+entry.getValue());
        }

        /*
        方法三:通过KeySet或Values()遍历
         */


        System.out.println("MaxKey: "+getMaxKey(map));
        System.out.println("MaxValue: "+getMaxValue(map));
        System.out.println("KeyOfMaxValue: "+getKeyOfMaxValue(map));
    }

    public static Object getMaxKey(Map<Integer, Integer> map){
        if(map == null) return null;

        Set set = map.keySet();

        if(set.contains(null))
            set.remove(null);
        Object[] obj = set.toArray();
        Arrays.sort(obj);
        return obj[obj.length - 1];
    }

    public static Object getMaxValue(Map<Integer, Integer> map){
        if(map == null) return null;

        Collection collection = map.values();

        if(collection.contains(null))
            collection.remove(null);
        Object[] obj =  collection.toArray();

        Arrays.sort(obj);
        return obj[collection.size()-1];
    }

    public static Object getKeyOfMaxValue(Map<Integer, Integer> map){
        if(map == null) return null;

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if(entry.getValue() == (int) getMaxValue(map))
                    return entry.getKey();
        }

        return null;
    }

}

P.S. 这里的remove直接改变了Collection,如果需要不改变Collection。需要用到深拷贝。

上一篇 下一篇

猜你喜欢

热点阅读