Java基础-Map

Map的一些操作

package com.sandy.MapDemo;

import java.util.*;

public class MapDemo {

    public static void main(String[] args) {

        Map map = new HashMap();
        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 entry : map.entrySet()) {
            System.out.println("key:"+entry.getKey()+"  value: "+entry.getValue());
        }

        /*
        方法二:通过Iterator遍历
         */
        System.out.println("遍历Map集合Key值: ");
        Iterator> iteratorEntry = map.entrySet().iterator();
        while(iteratorEntry.hasNext()){
            Map.Entry 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 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 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 map){
        if(map == null) return null;

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

        return null;
    }

}

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

你可能感兴趣的:(Java基础-Map)