Java HashMap 是 Java 中最流行的 Collection 类之一. Java HashMap 是基于 Hash 表的实现。
Java 哈希地图
Some of the important points about HashMap in Java are;
- Java HashMap 允许 null 密钥和 null 值
- HashMap 不是一个有序的集合。您可以通过密钥集重复 HashMap 条目,但它们不保证在 HashMap 添加的顺序下
- HashMap 几乎与 Hashtable 相似,但它不同步,允许 null 密钥和值
- HashMap 使用其内部类 Node<K,V> 来存储地图条目
- HashMap 存储多个单链接列表中的条目,称为 buckets 或 bins。 默认的密钥和值是 16 个,并且它始终是 2.
Java HashMap 开发者
Java HashMap 提供四个构建器。
- 公共HashMap(): 最常用的HashMap构建器. 本构建器将创建一个空的HashMap,默认初始容量为16和负载因子为0.75
- 公共HashMap(int initialCapacity):这个HashMap构建器被用来指定初始容量和0.75负载因子。如果您知道在HashMap中存储的最大数目,则有助于避免重启。
- 公共HashMap(int initialCapacity, float loadFactor):本 HashMap构建器将创建一个空的HashMap,具有指定的初始容量和负载因子。 如果您知道在HashMap中存储的
Java HashMap 构建模型
下面的代码片段显示了使用上述所有构建程序的HashMap示例。
1Map<String, String> map1 = new HashMap<>();
2
3Map<String, String> map2 = new HashMap<>(2^5);
4
5Map<String, String> map3 = new HashMap<>(32,0.80f);
6
7Map<String,String> map4 = new HashMap<>(map1);
Java HashMap 方法
让我们来看看 Java 中的 HashMap 的重要方法。
- ** 公之于众(): 此 HashMap 方法将删除所有映射, HashMap 将变为空 。 (_)
(英语). 2. ** 公共布尔包含 密钥( E) 对象键): 此方法返回
true
如果密钥存在, 否则它会返回false
。 () (英语). ** 公共布尔包含 数值( 对象值) **: 此 HashMap 方法返回真值, 如果该值存在其它错误 。 () (英语). 4. ** 公用套件<地图. Entry<K,V>>> accessSet () **: 此方法返回 HashMap 映射的 Set 视图 。 此集由地图支持,因此对地图的更改在集中被反映,反之亦然. - ** 公共 V 获得(对象密钥) **: 返回映射到指定密钥的值, 如果没有映射密钥则无效 。
- ** publishlean isEmpty () ** : 如果不存在密钥值映射, 则返回 true 方法 。
- ** 公用Set
keySet () **: 返回 a 设定此地图中的密钥视图 。 集由地图支持,因此对地图的修改在集中反映,反之亦然. - ** Public V pet(K键,V值)**: 将指定的值与本地图中指定的密钥关联起来。 如果之前的地图包含密钥的映射,则旧值被替换.
- ** public public put(地图 < ?) 扩展K,? 扩展 V > m): 从指定的地图复制到此地图的所有映射 。 这些映射将取代此映射对于当前指定的映射中的任何密钥的任何映射 。 () )10 (英语). ** 公共 V 删除(对象密钥) **: 在当前情况下从此地图中删除指定的密钥映射 。 () )11 (英语). ** 公用单位(): 返回此地图中的密钥值映射数 。
- ** 公共收藏 < V> 值 () ** : 返回此地图所载值的收藏视图。 所收由地图作后盾,故所收地图之变化也相克而相克. ( (英语)
在Java 8中引入的HashMap中有很多新方法。
- 联合国 ** 公开V计算 如果发文( K 密钥, 函数 < ?) 超级K? 扩展 V > 映射功能**: 如果指定的密钥与一个值(或被映射为无效)没有关系,这种方法试图使用给定的映射函数来计算其值,并输入到HashMap中,除非Null.
- ** 公共 V 计算 If Present( K 密钥, 双功能 < ? 超级K,超级V, 扩展V >再映射功能): 如果指定的密钥的值为有值和非有值,则尝试计算给定密钥及其当前映射值的新映射. 3。 ** 公用 V 计算( K 密钥, BiFunction < ? 超级K,超级V, 扩展V >再映射功能): 此 HashMap 方法试图计算指定的密钥及其当前映射值的映射 。
- ** public void for Each( Bicconcumer < ?) 超级K, ? 超级V > 动作) : 此方法执行此地图中每个条目的指定动作 。 5 。 ** 公用 V 获得 OrDefault () 对象键, V 默认值) ** : 与获得相同, 除了默认 如果找不到指定密钥的映射, 则返回值 。 6 ** 公用 V 合并( K 键, V 值, BiFunction < ?) 超级V 超级V 扩展V >再映射功能: 如果指定的密钥尚未与一个值相关联或与无效相关联,则将其与给定的非null值相关联. 否则,将相关值替换为给定的再映射函数的结果,或者如果结果无效则删除.
- ** 公用 V petifAbsent(K键,V值)**: 如果指定的密钥尚未与一个值( 或被映射为无效) 关联到给定值并返回为无效, 否则返回当前值 。
- ** 公开布尔去除( P) 对象密钥, 对象值)**: 仅在当前映射到指定值时才删除指定的密钥条目 。
- ** 公用布尔替换(K键、V旧Value、V新Value): 仅在当前映射到指定值时替换指定密钥的条目 。 (_) )10 (英语). ** 公用V替换(K键,V值): 仅在指定的密钥当前映射到某个值时才替换该项 。 () )11 (英语). ** 公共空白替换 全部( 函数 < ?) 超级 K, 超级 V, 扩展 V > 函数) ** : 将每个条目的值替换为在该条目上引用给定函数的结果。 () (英语)
Java HashMap 示例
以下是用于 HashMap 常用的方法的一种简单的 java 程序。
1package com.journaldev.examples;
2
3import java.util.Collection;
4import java.util.HashMap;
5import java.util.Map;
6import java.util.Map.Entry;
7import java.util.Set;
8
9public class HashMapExample {
10
11 public static void main(String[] args) {
12
13 Map<String, String> map = new HashMap<>();
14
15 map.put("1", "1"); // put example
16 map.put("2", "2");
17 map.put("3", "3");
18 map.put("4", null); // null value
19 map.put(null, "100"); // null key
20
21 String value = map.get("3"); // get example
22 System.out.println("Key = 3, Value = " + value);
23
24 value = map.getOrDefault("5", "Default Value");
25 System.out.println("Key = 5, Value=" + value);
26
27 boolean keyExists = map.containsKey(null);
28 boolean valueExists = map.containsValue("100");
29
30 System.out.println("keyExists=" + keyExists + ", valueExists=" + valueExists);
31
32 Set<Entry<String, String>> entrySet = map.entrySet();
33 System.out.println(entrySet);
34
35 System.out.println("map size=" + map.size());
36
37 Map<String, String> map1 = new HashMap<>();
38 map1.putAll(map);
39 System.out.println("map1 mappings= " + map1);
40
41 String nullKeyValue = map1.remove(null);
42 System.out.println("map1 null key value = " + nullKeyValue);
43 System.out.println("map1 after removing null key = " + map1);
44
45 Set<String> keySet = map.keySet();
46 System.out.println("map keys = " + keySet);
47
48 Collection<String> values = map.values();
49 System.out.println("map values = " + values);
50
51 map.clear();
52 System.out.println("map is empty=" + map.isEmpty());
53
54 }
55
56}
下面是上面的Java HashMap示例程序的输出。
1Key = 3, Value = 3
2Key = 5, Value=Default Value
3keyExists=true, valueExists=true
4[null=100, 1=1, 2=2, 3=3, 4=null]
5map size=5
6map1 mappings= {null=100, 1=1, 2=2, 3=3, 4=null}
7map1 null key value = 100
8map1 after removing null key = {1=1, 2=2, 3=3, 4=null}
9map keys = [null, 1, 2, 3, 4]
10map values = [100, 1, 2, 3, null]
11map is empty=true
如何在 Java 中使用 HashMap?
HashMap in java use it's inner class Node<K,V> for storing mappings. HashMap works on hashing algorithm and uses hashCode() and equals() method on key for get and put operations. HashMap use singly linked list to store elements, these are called bins or buckets. When we call put method, hashCode of key is used to determine the bucket that will be used to store the mapping. Once bucket is identified, hashCode is used to check if there is already a key with same hashCode or not. If there is an existing key with same hashCode, then equals() method is used on key. If equals returns true, then value is overwritten, otherwise a new mapping is made to this singly linked list bucket. If there is no key with same hashCode then mapping is inserted into the bucket. For HashMap get operation, again key hashCode is used to determine the bucket to look for the value. After bucket is identified, entries are traversed to find out the Entry using hashCode and equals method. If match is found, value is returned otherwise null is returned. There are much more things involved such as hashing algorithm to get the bucket for the key, rehashing of mappings etc. But for our working, just remember that HashMap operations work on Key and good implementation of hashCode and equals method is required to avoid unwanted behaviour. Below image shows the explanation of get and put operations. Recommended Read: hashCode and equals method importance in Java
Java HashMap 加载因子
加载因子用于找出HashMap将被重新加速和桶大小将增加时。桶或容量的默认值为16和加载因子为0.75。加载的门槛是通过加倍容量和负载因子来计算的。所以默认的门槛值将是12。所以当HashMap将有超过12个地图时,它将被重新加速,并且堆栈的数量将被增加到接下来的功率2即32。 请注意,HashMap的容量始终是2的功率。 默认的加载因子为0.75提供了空间和时间的复杂性之间的良好交易。 但您可以根据您的要求将其设置为不同的值。 如果您想要节省空间,则可以将其值增加到0.80或0.90,但接收/输出操作将需要更多的时间
Java HashMap 键盘
Java HashMap keySet 方法返回了 HashMap 中的密钥的 Set 视图. 此 Set 视图由 HashMap 支持,并且在 Set 和 vice versa 中反映了 HashMap 中的任何更改。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.HashSet;
5import java.util.Map;
6import java.util.Set;
7
8public class HashMapKeySetExample {
9
10 public static void main(String[] args) {
11
12 Map<String, String> map = new HashMap<>();
13 map.put("1", "1");
14 map.put("2", "2");
15 map.put("3", "3");
16
17 Set<String> keySet = map.keySet();
18 System.out.println(keySet);
19
20 map.put("4", "4");
21 System.out.println(keySet); // keySet is backed by Map
22
23 keySet.remove("1");
24 System.out.println(map); // map is also modified
25
26 keySet = new HashSet<>(map.keySet()); // copies the key to new Set
27 map.put("5", "5");
28 System.out.println(keySet); // keySet is not modified
29 }
30
31}
上面的程序的输出将清楚地说明 keySet 是由地图支持的。
1[1, 2, 3]
2[1, 2, 3, 4]
3{2=2, 3=3, 4=4}
4[2, 3, 4]
Java HashMap 价值观
Java HashMap 值方法返回地图中的值的集合视图. 此集合由 HashMap 支持,因此 HashMap 中的任何更改都会反映在值集合中,反之亦然. 下面的简单示例证实了 HashMap 值集合的这种行为。
1package com.journaldev.examples;
2
3import java.util.Collection;
4import java.util.HashMap;
5import java.util.Map;
6
7public class HashMapValuesExample {
8
9 public static void main(String[] args) {
10 Map<String, String> map = new HashMap<>();
11 map.put("1", "1");
12 map.put("2", "2");
13 map.put("3", null);
14 map.put("4", null);
15 map.put(null, "100");
16
17 Collection<String> values = map.values();
18 System.out.println("map values = " + values);
19
20 map.remove(null);
21 System.out.println("map values after removing null key = " + values);
22
23 map.put("5", "5");
24 System.out.println("map values after put = " + values);
25
26 System.out.println(map);
27 values.remove("1"); // changing values collection
28 System.out.println(map); // updates in map too
29
30 }
31
32}
上面的节目是下面的。
1map values = [100, 1, 2, null, null]
2map values after removing null key = [1, 2, null, null]
3map values after put = [1, 2, null, null, 5]
4{1=1, 2=2, 3=null, 4=null, 5=5}
5{2=2, 3=null, 4=null, 5=5}
Java HashMap 入口
Java HashMap entrySet 方法返回地图的 Set 视图. 此 entrySet 由 HashMap 支持,因此地图的任何更改都反映在输入集中,反之亦然。
1package com.journaldev.examples;
2
3import java.util.AbstractMap;
4import java.util.HashMap;
5import java.util.Iterator;
6import java.util.Map;
7import java.util.Map.Entry;
8import java.util.Set;
9
10public class HashMapEntrySetExample {
11
12 public static void main(String[] args) {
13 Map<String, String> map = new HashMap<>();
14 map.put("1", "1");
15 map.put("2", null);
16 map.put(null, "100");
17
18 Set<Entry<String,String>> entrySet = map.entrySet();
19 Iterator<Entry<String, String>> iterator = entrySet.iterator();
20 Entry<String, String> next = null;
21
22 System.out.println("map before processing = "+map);
23 System.out.println("entrySet before processing = "+entrySet);
24 while(iterator.hasNext()){
25 next = iterator.next();
26 System.out.println("Processing on: "+next.getValue());
27 if(next.getKey() == null) iterator.remove();
28 }
29
30 System.out.println("map after processing = "+map);
31 System.out.println("entrySet after processing = "+entrySet);
32
33 Entry<String, String> simpleEntry = new AbstractMap.SimpleEntry<String, String>("1","1");
34 entrySet.remove(simpleEntry);
35 System.out.println("map after removing Entry = "+map);
36 System.out.println("entrySet after removing Entry = "+entrySet);
37 }
38
39}
下面是由上面的程序产生的输出。
1map before processing = {null=100, 1=1, 2=null}
2entrySet before processing = [null=100, 1=1, 2=null]
3Processing on: 100
4Processing on: 1
5Processing on: null
6map after processing = {1=1, 2=null}
7entrySet after processing = [1=1, 2=null]
8map after removing Entry = {2=null}
9entrySet after removing Entry = [2=null]
Java HashMap 不存在
在Java 8中引入的 HashMap putIfAbsent方法的一个简单示例。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5
6public class HashMapPutIfAbsentExample {
7
8 public static void main(String[] args) {
9 Map<String, String> map = new HashMap<>();
10 map.put("1", "1");
11 map.put("2", null);
12 map.put(null, "100");
13
14 System.out.println("map before putIfAbsent = "+map);
15 String value = map.putIfAbsent("1", "4");
16 System.out.println("map after putIfAbsent = "+map);
17 System.out.println("putIfAbsent returns: "+value);
18
19 System.out.println("map before putIfAbsent = "+map);
20 value = map.putIfAbsent("3", "3");
21 System.out.println("map after putIfAbsent = "+map);
22 System.out.println("putIfAbsent returns: "+value);
23 }
24
25}
上述方案的结果是;
1map before putIfAbsent = {null=100, 1=1, 2=null}
2map after putIfAbsent = {null=100, 1=1, 2=null}
3putIfAbsent returns: 1
4map before putIfAbsent = {null=100, 1=1, 2=null}
5map after putIfAbsent = {null=100, 1=1, 2=null, 3=3}
6putIfAbsent returns: null
Java HashMap 预览
HashMap forEach 方法在 Java 8 中被引入,它是一个非常有用的方法,可以为地图中的每个条目执行给定的操作,直到所有条目都被处理或该操作引发了例外。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.function.BiConsumer;
6
7public class HashMapForEachExample {
8
9 public static void main(String[] args) {
10 Map<String, String> map = new HashMap<>();
11 map.put("1", "1");
12 map.put("2", null);
13 map.put(null, "100");
14
15 BiConsumer<String, String> action = new MyBiConsumer();
16 map.forEach(action);
17
18 //lambda expression example
19 System.out.println("\nHashMap forEach lambda example\n");
20 map.forEach((k,v) -> {System.out.println("Key = "+k+", Value = "+v);});
21 }
22
23}
24
25class MyBiConsumer implements BiConsumer<String, String> {
26
27 @Override
28 public void accept(String t, String u) {
29 System.out.println("Key = " + t);
30 System.out.println("Processing on value = " + u);
31 }
32
33}
上述HashMap forEach示例程序的输出是;
1Key = null
2Processing on value = 100
3Key = 1
4Processing on value = 1
5Key = 2
6Processing on value = null
7
8HashMap forEach lambda example
9
10Key = null, Value = 100
11Key = 1, Value = 1
12Key = 2, Value = null
Java HashMap 取代所有
HashMap replaceAll 方法可以用来取代每个输入的值,以便在该输入上调用给定函数的结果。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.function.BiFunction;
6
7public class HashMapReplaceAllExample {
8
9 public static void main(String[] args) {
10 Map<String, String> map = new HashMap<>();
11 map.put("1", "1");
12 map.put("2", "2");
13 map.put(null, "100");
14
15 System.out.println("map before replaceAll = " + map);
16 BiFunction<String, String, String> function = new MyBiFunction();
17 map.replaceAll(function);
18 System.out.println("map after replaceAll = " + map);
19
20 // replaceAll using lambda expressions
21 map.replaceAll((k, v) -> {
22 if (k != null) return k + v;
23 else return v;});
24 System.out.println("map after replaceAll lambda expression = " + map);
25
26 }
27
28}
29
30class MyBiFunction implements BiFunction<String, String, String> {
31
32 @Override
33 public String apply(String t, String u) {
34 if (t != null)
35 return t + u;
36 else
37 return u;
38 }
39
40}
上面的 HashMap 代替所有程序的输出是;
1map before replaceAll = {null=100, 1=1, 2=2}
2map after replaceAll = {null=100, 1=11, 2=22}
3map after replaceAll lambda example = {null=100, 1=111, 2=222}
Java HashMap 计算机
HashMap computeIfAbsent 方法只计算值,如果密钥不在地图中,然后将其放入地图中,如果它不是 null。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.function.Function;
6
7public class HashMapComputeIfAbsent {
8
9 public static void main(String[] args) {
10 Map<String, String> map = new HashMap<>();
11 map.put("1", "10");
12 map.put("2", "20");
13 map.put(null, "100");
14
15 Function<String, String> function = new MyFunction();
16 map.computeIfAbsent("3", function); //key not present
17 map.computeIfAbsent("2", function); //key already present
18
19 //lambda way
20 map.computeIfAbsent("4", v -> {return v;});
21 map.computeIfAbsent("5", v -> {return null;}); //null value won't get inserted
22 System.out.println(map);
23 }
24
25}
26
27class MyFunction implements Function<String, String> {
28
29 @Override
30 public String apply(String t) {
31 return t;
32 }
33
34}
上述方案的结果是;
1{null=100, 1=10, 2=20, 3=3, 4=4}
Java HashMap 计算机
Java HashMap computeIfPresent 方法在指定密钥存在且值不是 null 时重新计算值. 如果函数返回 null,则删除地图。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.function.BiFunction;
6
7public class HashMapComputeIfPresentExample {
8
9 public static void main(String[] args) {
10 Map<String, String> map = new HashMap<>();
11 map.put("1", "10");
12 map.put("2", "20");
13 map.put(null, "100");
14 map.put("10", null);
15
16 System.out.println("map before computeIfPresent = " + map);
17 BiFunction<String, String, String> function = new MyBiFunction1();
18 for (String key : map.keySet()) {
19 map.computeIfPresent(key, function);
20 }
21
22 System.out.println("map after computeIfPresent = " + map);
23 map.computeIfPresent("1", (k,v) -> {return null;}); // mapping will be removed
24 System.out.println("map after computeIfPresent = " + map);
25
26 }
27
28}
29
30class MyBiFunction1 implements BiFunction<String, String, String> {
31
32 @Override
33 public String apply(String t, String u) {
34 return t + u;
35 }
36
37}
由 HashMap computeIfPresent 生产的输出示例是;
1map before computeIfPresent = {null=100, 1=10, 2=20, 10=null}
2map after computeIfPresent = {null=null100, 1=110, 2=220, 10=null}
3map after computeIfPresent = {null=null100, 2=220, 10=null}
Java HashMap 计算机
如果要将函数应用于所有基于其密钥和值的映射,则应使用计算方法. 如果没有映射,并且使用此方法,则计算函数的值将为null。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5
6public class HashMapComputeExample {
7
8 public static void main(String[] args) {
9 Map<String, String> map = new HashMap<>();
10 map.put("1", "1");
11 map.put("2", "2");
12 map.put(null, "10");
13 map.put("10", null);
14
15 System.out.println("map before compute = "+map);
16 for (String key : map.keySet()) {
17 map.compute(key, (k,v) -> {return k+v;});
18 }
19 map.compute("5", (k,v) -> {return k+v;}); //key not present, v = null
20 System.out.println("map after compute = "+map);
21 }
22
23}
HashMap计算机的输出示例是;
1map before compute = {null=10, 1=1, 2=2, 10=null}
2map after compute = {null=null10, 1=11, 2=22, 5=5null, 10=10null}
Java 哈希地图 merge
如果指定的密钥不存在或与 null 相关联,则将其与给定的非 null 值相关联。
1package com.journaldev.examples;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.Map.Entry;
6
7public class HashMapMergeExample {
8
9 public static void main(String[] args) {
10 Map<String, String> map = new HashMap<>();
11 map.put("1", "1");
12 map.put("2", "2");
13 map.put(null, "10");
14 map.put("10", null);
15
16 for (Entry<String, String> entry : map.entrySet()) {
17 String key = entry.getKey();
18 String value = entry.getValue();
19 //merge throws NullPointerException if key or value is null
20 if(key != null && value != null)
21 map.merge(entry.getKey(), entry.getValue(),
22 (k, v) -> {return k + v;});
23 }
24 System.out.println(map);
25
26 map.merge("5", "5", (k, v) -> {return k + v;}); // key not present
27 System.out.println(map);
28
29 map.merge("1", "1", (k, v) -> {return null;}); // method return null, so remove
30 System.out.println(map);
31
32 }
33
34}
上述方案的结果是;
1{null=10, 1=11, 2=22, 10=null}
2{null=10, 1=11, 2=22, 5=5, 10=null}
3{null=10, 2=22, 5=5, 10=null}
对于Java中的HashMap来说,这就是全部,我希望没有什么重要的东西被错过了,如果你喜欢它,也可以与其他人分享。