public final class MapUtil extends Object
Map
工具类.
hashCode重要么?
对于List
集合、数组而言,不重要,他就是一个累赘;
但是对于HashMap
、HashSet
、Hashtable
而言,它变得异常重要.在Java中hashCode的实现总是伴随着equals,他们是紧密配合的,你要是自己设计了其中一个,就要设计另外一个。
整个处理流程是:
![]()
- 判断两个对象的hashcode是否相等,若不等,则认为两个对象不等,完毕,若相等,则比较equals。
- 若两个对象的equals不等,则可以认为两个对象不等,否则认为他们相等。
Map
:
interface/class 说明 Map
- An object that maps keys to values.
- A map cannot contain duplicate keys
- Takes the place of the Dictionary class
HashMap
- Hash table based implementation of the Map interface.
- permits null values and the null key.
- makes no guarantees as to the order of the map
扩容:
HashMap
初始容量HashMap.DEFAULT_INITIAL_CAPACITY
是16,DEFAULT_LOAD_FACTOR 是0.75java.util.HashMap#addEntry
是 2 * table.length 2倍
LinkedHashMap
Note that: insertion order is not affected if a key is re-inserted into the map.
- Hash table and linked list implementation of the Map interface,
- with predictable iteration order.
TreeMap
- A Red-Black tree based NavigableMap implementation
- sorted according to the natural ordering of its keys, or by a Comparator.
- 默认情况 key不能为null,如果传入了
NullComparator
那么key 可以为null.Hashtable
- This class implements a hashtable, which maps keys to values.
- synchronized.
- Any non-null object can be used as a key or as a value.
Properties
- The Properties class represents a persistent set of properties.
- can be saved to a stream or loaded from a stream.
- Each key and its corresponding value in the property list is a string.
IdentityHashMap
- using reference-equality in place of object-equality when comparing keys (and values).
- 使用==代替equals()对key进行比较的散列表.专为特殊问题而设计的
注意:此类不是 通用 Map 实现!它有意违反 Map 的常规协定,此类设计仅用于其中需要引用相等性语义的罕见情况
WeakHashMap
- A hashtable-based Map implementation with weak keys.
- 它对key实行"弱引用",如果一个key不再被外部所引用,那么该key可以被GC回收
EnumMap
- A specialized Map implementation for use with enum type keys.
- Enum maps are maintained in the natural order of their keys
- 不允许空的key
AbstractMap.SimpleEntry
,
MapUtils
,
"com.google.common.collect.Maps"Modifier and Type | Method and Description |
---|---|
static <K,O,V> Map<K,V> |
extractSubMap(Map<K,O> map,
K[] includeKeys,
String extractPropertyName)
以参数
map 的key为key,以参数 map value的指定extractPropertyName
属性值为值,拼装成新的map返回. |
static <K,O,V> Map<K,V> |
extractSubMap(Map<K,O> map,
String extractPropertyName)
以参数
map 的key为key,以参数 map value的指定extractPropertyName 属性值为值,拼装成新的map返回. |
static <K,V> Map.Entry<K,V> |
get(Map<K,V> map,
int index)
根据索引来获得map 的entry.
|
static <K,T> Map<K,T> |
getSubMap(Map<K,T> map,
Iterable<K> keys)
获得一个
map 中,按照指定的keys 整理成新的map. |
static <K,T> Map<K,T> |
getSubMap(Map<K,T> map,
K... keys)
获得一个
map 中,按照指定的keys 整理成新的map. |
static <K,T> Map<K,T> |
getSubMapExcludeKeys(Map<K,T> map,
Iterable<K> excludeKeys)
获得 sub map(排除指定的 excludeKeys).
|
static <K,T> Map<K,T> |
getSubMapExcludeKeys(Map<K,T> map,
K... excludeKeys)
获得 sub map(排除指定的 excludeKeys).
|
static <K,V> Map<V,K> |
invertMap(Map<K,V> map)
将
map 的key和value互转. |
static <K,V> ConcurrentHashMap<K,V> |
newConcurrentHashMap()
New concurrent hash map.
|
static <K,V> ConcurrentHashMap<K,V> |
newConcurrentHashMap(int expectedSize)
创建
ConcurrentHashMap 实例,拥有足够的 "initial capacity" 应该控制expectedSize elements without growth. |
static <K,V> ConcurrentHashMap<K,V> |
newConcurrentHashMap(Map<K,V> map)
New concurrent hash map.
|
static <K,V> HashMap<K,V> |
newHashMap()
创建
HashMap 实例. |
static <K,V> HashMap<K,V> |
newHashMap(int expectedSize)
创建
HashMap 实例,拥有足够的 "initial capacity" 应该控制expectedSize elements without growth. |
static <K,V> HashMap<K,V> |
newHashMap(Map<K,V> map)
New hash map.
|
static <K,V> LinkedHashMap<K,V> |
newLinkedHashMap()
创建
LinkedHashMap 实例. |
static <K,V> LinkedHashMap<K,V> |
newLinkedHashMap(int expectedSize)
创建
LinkedHashMap 实例,拥有足够的 "initial capacity" 应该控制expectedSize elements without growth. |
static <K,V> LinkedHashMap<K,V> |
newLinkedHashMap(Map<K,V> map)
New linked hash map.
|
static <K extends Comparable,V> |
newTreeMap()
New tree map.
|
static <K extends Comparable,V> |
newTreeMap(Map<K,V> map)
New tree map.
|
static <K,V> void |
putAllIfNotNull(Map<K,V> map,
Map<? extends K,? extends V> m)
仅当
null != map && null != m ,才会进行 map.putAll(m) 操作 |
static <K,V> void |
putIfValueNotNull(Map<K,V> map,
K key,
V value)
仅当
null != map 并且 null != value 才将key/value put到map中. |
static <K,V> void |
putIfValueNotNullOrEmpty(Map<K,V> map,
K key,
V value)
仅当
null != map 并且 isNotNullOrEmpty(value) 才将key/value put到map中. |
static <K,V> Map<K,List<V>> |
putMultiValue(Map<K,List<V>> map,
K key,
V value)
往 map 中put 指定 key value(多值形式).
|
static <K> Map<K,BigDecimal> |
putSumValue(Map<K,BigDecimal> map,
K key,
Number value)
将
key 和value 累加的形式put到 map中,如果map 中存在key ,那么累加value 值;如果不存在那么直接put. |
static <K> Map<K,Integer> |
putSumValue(Map<K,Integer> map,
K key,
Integer value)
将
key 和value 累加的形式put到 map中,如果map 中存在key ,那么累加value 值;如果不存在那么直接put. |
static <K,V> Map<K,V> |
removeKeys(Map<K,V> map,
K... keys)
删除
map 的指定的 keys . |
static <K> Map<K,String[]> |
toArrayValueMap(Map<K,String> singleValueMap)
将单值的
singleValueMap 转成多值的map. |
static <K,V> Map<K,V> |
toSingleValueMap(Map<K,V[]> arrayValueMap)
将多值的
arrayValueMap 转成单值的map. |
public static <K,V> Map.Entry<K,V> get(Map<K,V> map, int index)
- 传入的map 最好是
LinkedHashMap
,EnumMap
等自身有顺序的map,否则如HashMap
每次结果都不一样
场景: 获得下面bookSectionUrlMap 第一个entry value值
public void createFile(Novel novel){ Map<String, String>
bookSectionUrlMap = parseBookSectionUrlMap(novel); if (isNullOrEmpty(bookSectionUrlMap)){ LOGGER.warn("bookSectionUrlMap is null/empty,Perhaps you read the latest chapter"); return; } //--------------------------------------------------------------- String beginName = null; // 开始章节名称 for (Map.Entry<String, String>
entry : bookSectionUrlMap.entrySet()){ String sectionName = entry.getValue(); if (isNullOrEmpty(beginName)){ beginName = sectionName;//①这里纯粹只是为了获得 map 第一个 entry value 值 } try{ //do some big logic }catch (ChapterParseException e){ break; //如果出现了异常 就跳出 } } //--------------------------------------------------------------- write(novel, beginName); // do something logic }对于上述代码 ①处的代码,虽然只是寥寥几行,但是会减低代码的可读性,也不利于循环体代码抽取,通过sonar 扫描的时候,明显方法的复杂度很高
此时,你可以优化成:public void createFile(Novel novel){ Map<String, String>
bookSectionUrlMap = parseBookSectionUrlMap(novel); if (isNullOrEmpty(bookSectionUrlMap)){ LOGGER.warn("bookSectionUrlMap is null/empty,Perhaps you read the latest chapter"); return; } //--------------------------------------------------------------- for (Map.Entry<String, String>
entry : bookSectionUrlMap.entrySet()){ try{ //do some big logic }catch (ChapterParseException e){ break; //如果出现了异常 就跳出 } } //--------------------------------------------------------------- write(novel, MapUtil.get(bookSectionUrlMap, 0).getValue()); // do something logic }
K
- the key typeV
- the value typemap
- 最好是 LinkedHashMap
,EnumMap
等自身有顺序的map,否则每次出来的结果都不一样index
- the indexmap
是null,抛出 NullPointerException
IndexOutOfBoundsException
- if the index is invalidIterableUtils.get(Iterable, int)
,
CollectionUtils.get(Map, int)
public static <K,V> Map<K,V> toSingleValueMap(Map<K,V[]> arrayValueMap)
arrayValueMap
转成单值的map.
Map返回:<String, String[]>
arrayValueMap = new LinkedHashMap<>
(); arrayValueMap.put("province", new String[] { "江苏省" }); arrayValueMap.put("city", new String[] { "南通市" }); LOGGER.info(JsonUtil.format(ParamUtil.toSingleValueMap(arrayValueMap)));{ "province": "江苏省", "city": "南通市" }
如果arrayValueMap其中有key的值是多值的数组,那么转换到新的map中的时候,value取第一个值,
Map返回:<String, String[]>
arrayValueMap = new LinkedHashMap<>
(); arrayValueMap.put("province", new String[] { "浙江省", "江苏省" }); arrayValueMap.put("city", new String[] { "南通市" }); LOGGER.info(JsonUtil.format(ParamUtil.toSingleValueMap(arrayValueMap)));{ "province": "浙江省", "city": "南通市" }
- 返回的map是 提取参数
arrayValueMap
的key做为key,value数组的第一个元素做value
- 返回的是
LinkedHashMap
,保证顺序和参数arrayValueMap
顺序相同- 和该方法正好相反的是
toArrayValueMap(Map)
K
- the key typeV
- the value typearrayValueMap
- the array value maparrayValueMap
是null或者empty,那么返回 Collections.emptyMap()
,arrayValueMap
其中有key的值是多值的数组,那么转换到新的map中的时候,value取第一个值,arrayValueMap
其中有key的value是null,那么转换到新的map中的时候,value以 null替代public static <K> Map<K,String[]> toArrayValueMap(Map<K,String> singleValueMap)
singleValueMap
转成多值的map.
Map返回:<String, String>
singleValueMap = new LinkedHashMap<>
(); singleValueMap.put("province", "江苏省"); singleValueMap.put("city", "南通市"); LOGGER.info(JsonUtil.format(ParamUtil.toArrayValueMap(singleValueMap)));{ "province": ["江苏省"], "city": ["南通市"] }
- 返回的是
LinkedHashMap
,保证顺序和参数singleValueMap
顺序相同- 和该方法正好相反的是
toSingleValueMap(Map)
K
- the key typesingleValueMap
- the name and value mapsingleValueMap
是null或者empty,那么返回 Collections.emptyMap()
singleValueMap
将value转成数组,返回新的 arrayValueMap
public static <K,V> void putIfValueNotNull(Map<K,V> map, K key, V value)
null != map 并且 null != value
才将key/value put到map中.
- 如果
map
是null,什么都不做- 如果
value
是null,也什么都不做- 如果
key
是null,依照map
的key
是否允许是null的 规则
K
- the key typeV
- the value typemap
- the map to add tokey
- the keyvalue
- the valueMapUtils.safeAddToMap(Map, Object, Object)
public static <K,V> void putAllIfNotNull(Map<K,V> map, Map<? extends K,? extends V> m)
null != map && null != m
,才会进行 map.putAll(m)
操作
对于以下代码:
if (isNotNullOrEmpty(specialSignMap)){ map.putAll(specialSignMap); }可以重构成:MapUtil.putAllIfNotNull(map, specialSignMap)
K
- the key typeV
- the value typemap
- the mapm
- mappings to be stored in this mapMap.putAll(Map)
public static <K,V> void putIfValueNotNullOrEmpty(Map<K,V> map, K key, V value)
null != map 并且 isNotNullOrEmpty(value)
才将key/value put到map中.
- 如果
map
是null,什么都不做- 如果
value
是null或者empty,也什么都不做- 如果
key
是null,依照map
的key
是否允许是null的规则
对于以下代码:
if (isNotNullOrEmpty(taoBaoOAuthLoginForCodeEntity.getState())){ nameAndValueMap.put("state", taoBaoOAuthLoginForCodeEntity.getState()); }可以重构成:MapUtil.putIfValueNotNullOrEmpty(nameAndValueMap, "state", taoBaoOAuthLoginForCodeEntity.getState());
K
- the key typeV
- the value typemap
- the mapkey
- the keyvalue
- the valuepublic static <K> Map<K,Integer> putSumValue(Map<K,Integer> map, K key, Integer value)
key
和value
累加的形式put到 map中,如果map
中存在key
,那么累加value
值;如果不存在那么直接put.
Map返回:<String, Integer>
map = new HashMap<>
(); MapUtil.putSumValue(map, "1000001", 5); MapUtil.putSumValue(map, "1000002", 5); MapUtil.putSumValue(map, "1000002", 5); LOGGER.debug(JsonUtil.format(map));{ "1000001": 5, "1000002": 10 }
对于以下代码:
if (disadvantageMap.containsKey(disadvantageToken)){ disadvantageMap.put(disadvantageToken, disadvantageMap.get(disadvantageToken) + 1); }else{ disadvantageMap.put(disadvantageToken, 1); }可以重构成:MapUtil.putSumValue(disadvantageMap, disadvantageToken, 1);
K
- the key typemap
- the mapkey
- the keyvalue
- 数值,不能为null,可以是负数map
是null,抛出 NullPointerException
value
是null,抛出 NullPointerException
HashBag
,
MutableInt
,
"java.util.Map#getOrDefault(Object, Object)",
most-efficient-way-to-
increment-a-map-value-in-javapublic static <K> Map<K,BigDecimal> putSumValue(Map<K,BigDecimal> map, K key, Number value)
key
和value
累加的形式put到 map中,如果map
中存在key
,那么累加value
值;如果不存在那么直接put.
常用于数据统计, 比如 AggregateUtil.groupSum(Iterable, String, String)
Map返回:<String, BigDecimal>
map = new HashMap<>
(); MapUtil.putSumValue(map, "1000001", 5); MapUtil.putSumValue(map, "1000002", 5); MapUtil.putSumValue(map, "1000002", 5); LOGGER.debug(JsonUtil.format(map));{ "1000001": 5, "1000002": 10 }
K
- the key typemap
- the mapkey
- the keyvalue
- 数值,不能为null,可以是负数map
是null,抛出 NullPointerException
value
是null,抛出 NullPointerException
HashBag
,
"java.util.Map#getOrDefault(Object, Object)",
most-efficient-way-to-
increment-a-map-value-in-javapublic static <K,V> Map<K,List<V>> putMultiValue(Map<K,List<V>> map, K key, V value)
- map已经存在相同名称的key,那么value以list的形式累加.
- 如果map中不存在指定名称的key,那么会构建一个ArrayList
Map返回:<String, List<String>>
mutiMap = newLinkedHashMap(2); MapUtil.putMultiValue(mutiMap, "name", "张飞"); MapUtil.putMultiValue(mutiMap, "name", "关羽"); MapUtil.putMultiValue(mutiMap, "age", "30"); LOGGER.debug(JsonUtil.format(mutiMap));{ "name": [ "张飞", "关羽" ], "age": ["30"] }
private void putItemToMap(Map可以重构成:<String, List<Item>>
map,String tagName,Item item){ List<Item>
itemList = map.get(tagName); if (isNullOrEmpty(itemList)){ itemList = new ArrayList<Item>
(); } itemList.add(item); map.put(tagName, itemList); }private void putItemToMap(Map<String, List<Item>>
map,String tagName,Item item){ com.feilong.core.util.MapUtil.putMultiValue(map, tagName, item); }
K
- the key typeV
- the value typemap
- the mapkey
- the keyvalue
- the valuemap
是null,抛出 NullPointerException
MultiValuedMap
,
IterableMap
,
MultiMapUtils
,
AbstractMultiValuedMap
@SafeVarargs public static <K,T> Map<K,T> getSubMap(Map<K,T> map, K... keys)
map
中,按照指定的keys
整理成新的map.
- 原
map
不变- 返回的map为
LinkedHashMap
,key的顺序 按照参数keys
的顺序- 如果循环的 key不在map key里面,则忽略该key,并输出debug level log
Map返回:<String, Integer>
map = new HashMap<>
(); map.put("a", 3007); map.put("b", 3001); map.put("c", 3001); map.put("d", 3003); LOGGER.debug(JsonUtil.format(MapUtil.getSubMap(map, "a", "c")));{ "a": 3007, "c": 3001 }
K
- the key typeT
- the generic typemap
- the mapkeys
- 如果循环的 key不在map key里面,则忽略该key,并输出debug level logmap
是null或者empty,返回 Collections.emptyMap()
;keys
是null或者empty,直接返回 map
public static <K,T> Map<K,T> getSubMap(Map<K,T> map, Iterable<K> keys)
map
中,按照指定的keys
整理成新的map.
- 原
map
不变- 返回的map为
LinkedHashMap
,key的顺序 按照参数keys
的顺序- 如果循环的 key不在map key里面,则忽略该key,并输出debug level log
Map返回:<String, Integer>
map = new HashMap<>
(); map.put("a", 3007); map.put("b", 3001); map.put("c", 3001); map.put("d", 3003); LOGGER.debug(JsonUtil.format(MapUtil.getSubMap(map,toList("a", "c"))));{ "a": 3007, "c": 3001 }
K
- the key typeT
- the generic typemap
- the mapkeys
- 如果循环的 key不在map key里面,则忽略该key,并输出debug level logmap
是null或者empty,返回 Collections.emptyMap()
;keys
是null或者empty,直接返回 map
@SafeVarargs public static <K,T> Map<K,T> getSubMapExcludeKeys(Map<K,T> map, K... excludeKeys)
- 原
map
不变- 此方法可以提取
Collections.unmodifiableMap(Map)
- 返回值为
LinkedHashMap
,key的顺序按照参数map
的顺序
Map返回:<String, Integer>
map = new LinkedHashMap<>
(); map.put("a", 3007); map.put("b", 3001); map.put("c", 3002); map.put("g", -1005); LOGGER.debug(JsonUtil.format(MapUtil.getSubMapExcludeKeys(map, "a", "g", "m")));{ "b": 3001, "c": 3002 }
K
- the key typeT
- the generic typemap
- the mapexcludeKeys
- the keysmap
是null或者empty,返回 Collections.emptyMap()
;excludeKeys
是null或者empty,直接返回 map
public static <K,T> Map<K,T> getSubMapExcludeKeys(Map<K,T> map, Iterable<K> excludeKeys)
- 原
map
不变- 此方法可以提取
Collections.unmodifiableMap(Map)
- 返回值为
LinkedHashMap
,key的顺序按照参数map
的顺序
Map返回:<String, Integer>
map = new LinkedHashMap<>
(); map.put("a", 3007); map.put("b", 3001); map.put("c", 3002); map.put("g", -1005); LOGGER.debug(JsonUtil.format(MapUtil.getSubMapExcludeKeys(map, toList("a", "g", "m"))));{ "b": 3001, "c": 3002 }
K
- the key typeT
- the generic typemap
- the mapexcludeKeys
- the exclude keysmap
是null或者empty,返回 Collections.emptyMap()
;excludeKeys
是null或者empty,直接返回 map
@SafeVarargs public static <K,V> Map<K,V> removeKeys(Map<K,V> map, K... keys)
map
的指定的 keys
.
原
map
会改变,如果你只是需要从原map中获取非指定的
keys
,你可以调用getSubMapExcludeKeys(Map, Object...)
或者getSubMapExcludeKeys(Map, Iterable)
方法- 此方法删除不了
Collections.unmodifiableMap(Map)
- 如果
map
包含key,那么直接调用Map.remove(Object)
- 如果不包含,那么输出debug级别日志
Map返回:<String, String>
map = newLinkedHashMap(3); map.put("name", "feilong"); map.put("age", "18"); map.put("country", "china"); LOGGER.debug(JsonUtil.format(MapUtil.removeKeys(map, "country")));{ "name": "feilong", "age": "18" }
K
- the key typeV
- the value typemap
- the mapkeys
- the keysmap
是null,返回nullkeys
是null或者empty,直接返回 map
public static <K,V> Map<V,K> invertMap(Map<K,V> map)
map
的key和value互转.
- 这个操作map预先良好的定义.
- 如果传过来的map,不同的key有相同的value,那么返回的map(key)只会有一个(value),其他重复的key被丢掉了
Map返回:<String, Integer>
map = new HashMap<>
(); map.put("a", 3007); map.put("b", 3001); map.put("c", 3001); map.put("d", 3003); LOGGER.debug(JsonUtil.format(MapUtil.invertMap(map)));{ "3001": "c", "3007": "a", "3003": "d" }可以看出 b元素被覆盖了
K
- the key typeV
- the value typemap
- the mapmap
是null,返回 nullmap
是empty,返回 一个 new HashMapMapUtils.invertMap(Map)
public static <K,O,V> Map<K,V> extractSubMap(Map<K,O> map, String extractPropertyName)
map
的key为key,以参数 map
value的指定extractPropertyName
属性值为值,拼装成新的map返回.
- 返回map的顺序,按照参数 map key的顺序
Map返回:<Long, User>
map = new LinkedHashMap<>
(); map.put(1L, new User(100L)); map.put(2L, new User(200L)); map.put(5L, new User(500L)); map.put(4L, new User(400L)); LOGGER.debug(JsonUtil.format(MapUtil.extractSubMap(map, "id")));{ "1": 100, "2": 200, "5": 500, "4": 400 }
K
- key的类型O
- map value bean类型V
- map value bean相关 属性名称 extractPropertyName
的值类型map
- the mapextractPropertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamemap
是null或者empty,返回 Collections.emptyMap()
extractPropertyName
是null,抛出 NullPointerException
extractPropertyName
是blank,抛出 IllegalArgumentException
public static <K,O,V> Map<K,V> extractSubMap(Map<K,O> map, K[] includeKeys, String extractPropertyName)
map
的key为key,以参数 map
value的指定extractPropertyName
属性值为值,拼装成新的map返回.
- 如果在抽取的过程中,
map
没有某个includeKeys
,将会忽略该key的抽取,并输出 warn log- 如果参数
includeKeys
是null或者 empty,那么会抽取map所有的key- 返回map的顺序,按照参数includeKeys的顺序(如果includeKeys是null,那么按照map key的顺序)
Map返回:<Long, User>
map = new LinkedHashMap<>
(); map.put(1L, new User(100L)); map.put(2L, new User(200L)); map.put(53L, new User(300L)); map.put(5L, new User(500L)); map.put(6L, new User(600L)); map.put(4L, new User(400L)); Long[] includeKeys = { 5L, 4L }; LOGGER.debug(JsonUtil.format(MapUtil.extractSubMap(map, includeKeys, "id")));{ "5": 500, "4": 400 }
private Map<Long, Long>
constructPropertyIdAndItemPropertiesIdMap( String properties, Map<Long, PropertyValueSubViewCommand>
itemPropertiesIdAndPropertyValueSubViewCommandMap){ Long[] itemPropertiesIds = StoCommonUtil.toItemPropertiesIdLongs(properties); Map<Long, Long>
itemPropertiesIdAndPropertyIdMap = MapUtil .extractSubMap(itemPropertiesIdAndPropertyValueSubViewCommandMap, itemPropertiesIds, "propertyId"); return MapUtil.invertMap(itemPropertiesIdAndPropertyIdMap); }
K
- key的类型O
- map value bean类型V
- map value bean相关 属性名称 extractPropertyName
的值类型map
- the mapincludeKeys
- the include keysextractPropertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamemap
是null或者empty,返回 Collections.emptyMap()
extractPropertyName
是null,抛出 NullPointerException
extractPropertyName
是blank,抛出 IllegalArgumentException
includeKeys
是null或者empty, then will extract map total keyspublic static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap()
K
- the key typeV
- the value typeConcurrentHashMap
public static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap(Map<K,V> map)
K
- the key typeV
- the value typemap
- the mapmap
是null,抛出 NullPointerException
public static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap(int expectedSize)
ConcurrentHashMap
实例,拥有足够的 "initial capacity" 应该控制expectedSize
elements without growth.
This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7.
It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.
Map<String, String>
map = MapUtil.newConcurrentHashMap(3); map.put("name", "feilong"); map.put("age", "18"); map.put("address", "shanghai");
- 简化代码书写方式
以前你可能需要这么写代码:
Map<String, Map<Long, List<String>>>
map = new ConcurrentHashMap<String, Map<Long, List<String>>>
(16);如果你是使用JDK1.7或者以上,你可以使用钻石符:
Map<String, Map<Long, List<String>>>
map = new ConcurrentHashMap<>
(16);不过只要你是使用1.5+,你都可以写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newConcurrentHashMap(16);// 如果搭配static import 使用会更加简洁- 减少扩容次数
如果你要一次性初始一个能存放100个元素的map,并且不需要扩容,提高性能的话,你需要
Map<String, Map<Long, List<String>>>
map = new ConcurrentHashMap<String, Map<Long, List<String>>>
(100/0.75+1);使用这个方法,你可以直接写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newConcurrentHashMap(100);// 如果搭配static import 使用会更加简洁
K
- the key typeV
- the value typeexpectedSize
- the number of entries you expect to add to the returned mapConcurrentHashMap
with enough capacity to hold expectedSize
entries without resizingIllegalArgumentException
- 如果 expectedSize<
0public static <K extends Comparable,V> TreeMap<K,V> newTreeMap()
K
- the key typeV
- the value typeConcurrentHashMap
public static <K extends Comparable,V> TreeMap<K,V> newTreeMap(Map<K,V> map)
K
- the key typeV
- the value typemap
- the mapmap
是null,抛出 NullPointerException
public static <K,V> HashMap<K,V> newHashMap()
HashMap
实例.
Map<String, String>
newHashMap = MapUtil.newHashMap(); newHashMap.put("name", "feilong"); newHashMap.put("age", "18"); newHashMap.put("address", "shanghai");
- 简化代码书写方式
以前你可能需要这么写代码:
Map<String, Map<Long, List<String>>>
map = new HashMap<String, Map<Long, List<String>>>
();如果你是使用JDK1.7或者以上,你可以使用钻石符:
Map<String, Map<Long, List<String>>>
map = new HashMap<>
();不过只要你是使用1.5+,你都可以写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newHashMap(); // 如果搭配static import 使用会更加简洁
K
- the key typeV
- the value typeHashMap.HashMap()
public static <K,V> HashMap<K,V> newHashMap(Map<K,V> map)
K
- the key typeV
- the value typemap
- the mapmap
是null,抛出 NullPointerException
public static <K,V> HashMap<K,V> newHashMap(int expectedSize)
HashMap
实例,拥有足够的 "initial capacity" 应该控制expectedSize
elements without growth.
This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7.
It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.
Map<String, String>
newHashMap = MapUtil.newHashMap(3); newHashMap.put("name", "feilong"); newHashMap.put("age", "18"); newHashMap.put("address", "shanghai");
- 简化代码书写方式
以前你可能需要这么写代码:
Map<String, Map<Long, List<String>>>
map = new HashMap<String, Map<Long, List<String>>>
(16);如果你是使用JDK1.7或者以上,你可以使用钻石符:
Map<String, Map<Long, List<String>>>
map = new HashMap<>
(16);不过只要你是使用1.5+,你都可以写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newHashMap(16);// 如果搭配static import 使用会更加简洁- 减少扩容次数
如果你要一次性初始一个能存放100个元素的map,并且不需要扩容,提高性能的话,你需要
Map<String, Map<Long, List<String>>>
map = new HashMap<String, Map<Long, List<String>>>
(100/0.75+1);使用这个方法,你可以直接写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newHashMap(100);// 如果搭配static import 使用会更加简洁
K
- the key typeV
- the value typeexpectedSize
- the number of entries you expect to add to the returned mapHashMap
with enough capacity to hold expectedSize
entries without resizingIllegalArgumentException
- 如果 expectedSize<
0HashMap.HashMap(int)
public static <K,V> LinkedHashMap<K,V> newLinkedHashMap()
LinkedHashMap
实例.
Map<String, String>
map = MapUtil.newLinkedHashMap(); map.put("name", "feilong"); map.put("age", "18"); map.put("address", "shanghai");
- 简化代码书写方式
以前你可能需要这么写代码:
Map<String, Map<Long, List<String>>>
map = new LinkedHashMap<String, Map<Long, List<String>>>
();如果你是使用JDK1.7或者以上,你可以使用钻石符:
Map<String, Map<Long, List<String>>>
map = new LinkedHashMap<>
();不过只要你是使用1.5+,你都可以写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newLinkedHashMap();// 如果搭配static import 使用会更加简洁
K
- the key typeV
- the value typeLinkedHashMap.LinkedHashMap()
public static <K,V> LinkedHashMap<K,V> newLinkedHashMap(Map<K,V> map)
K
- the key typeV
- the value typemap
- the mapmap
是null,抛出 NullPointerException
public static <K,V> LinkedHashMap<K,V> newLinkedHashMap(int expectedSize)
LinkedHashMap
实例,拥有足够的 "initial capacity" 应该控制expectedSize
elements without growth.
This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7.
It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.
Map<String, String>
map = MapUtil.newLinkedHashMap(3); map.put("name", "feilong"); map.put("age", "18"); map.put("address", "shanghai");
- 简化代码书写方式
以前你可能需要这么写代码:
Map<String, Map<Long, List<String>>>
map = new LinkedHashMap<String, Map<Long, List<String>>>
(16);如果你是使用JDK1.7或者以上,你可以使用钻石符:
Map<String, Map<Long, List<String>>>
map = new LinkedHashMap<>
(16);不过只要你是使用1.5+,你都可以写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newLinkedHashMap(16);// 如果搭配static import 使用会更加简洁- 减少扩容次数
如果你要一次性初始一个能存放100个元素的map,并且不需要扩容,提高性能的话,你需要
Map<String, Map<Long, List<String>>>
map = new LinkedHashMap<String, Map<Long, List<String>>>
(100/0.75+1);使用这个方法,你可以直接写成:
Map<String, Map<Long, List<String>>>
map = MapUtil.newLinkedHashMap(100);// 如果搭配static import 使用会更加简洁
K
- the key typeV
- the value typeexpectedSize
- the number of entries you expect to add to the returned mapLinkedHashMap
with enough capacity to hold expectedSize
entries without resizingIllegalArgumentException
- 如果 size<
0LinkedHashMap.LinkedHashMap(int)
Copyright © 2008-2019 by feilong