All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jcohy.lang.Maps Maven / Gradle / Ivy

The newest version!
package com.jcohy.lang;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Copyright  : 2015-2033 Beijing
 * Created by jiac on 2018/3/5 11:21.
 * ClassName  : DateUtils
 * Description  : 快捷操作Map相关工具
 */
public final class Maps {
    enum MapType {
        /**
         * 生成Map的类型
         */
        ConcurrentHashMap,
        HashMap,
        TreeMap
    }

    public static  HashMap hashMap(Object... keyValues) {
        return (HashMap) map(MapType.HashMap, keyValues);
    }

    public static  ConcurrentHashMap concurrentHashMap(Object... keyValues) {
        return (ConcurrentHashMap) map(MapType.HashMap, keyValues);
    }

    public static  TreeMap treeMap(Object... keyValues) {
        return (TreeMap) map(MapType.HashMap, keyValues);
    }

    private static  Map map(MapType mapType, Object... keyValues) {
        int length = keyValues.length;
        if (length % 2 == 0) {
            Map map;
            if (mapType.equals(MapType.ConcurrentHashMap)) {
                map = new ConcurrentHashMap<>(length / 2);
            } else if (mapType.equals(MapType.HashMap)) {
                map = new HashMap<>(length / 2);
            } else if (mapType.equals(MapType.TreeMap)) {
                map = new TreeMap<>();
            } else {
                throw new RuntimeException("不支持的Map类型!");
            }
            for (int i = 1; i < keyValues.length; i = i + 2) {
                //noinspection unchecked
                K key = (K) keyValues[i - 1];
                //noinspection unchecked
                V value = (V) keyValues[i];
                map.put(key, value);
            }
            return map;
        } else {
            throw new RuntimeException("键值对数目不匹配!");
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy