java中hashmap_Java HashMap – Java中的HashMap

java中hashmap

Java HashMap is one of the most popular Collection classes in java. Java HashMap is Hash table based implementation. HashMap in java extends AbstractMap class that implements Map interface.

Java HashMap是Java中最受欢迎的Collection类之一。 Java HashMap是基于哈希表的实现。 Java中的HashMap扩展了实现Map接口的AbstractMap类。

Java HashMap (Java HashMap)

Some of the important points about HashMap in Java are;

关于Java中的HashMap的一些重点是:

  1. Java HashMap allows null key and null values.

    Java HashMap允许空键和空值。
  2. HashMap is not an ordered collection. You can iterate over HashMap entries through keys set but they are not guaranteed to be in the order of their addition to the HashMap.

    HashMap不是有序集合。 您可以通过键集遍历HashMap条目,但不能保证它们按其添加到HashMap的顺序。
  3. HashMap is almost similar to Hashtable except that it’s unsynchronized and allows null key and values.

    HashMap几乎与Hashtable相似,但它是不同步的,并且允许空键和值。
  4. HashMap uses it’s inner class Node<K,V> for storing map entries.

    HashMap使用其内部类Node <K,V>来存储地图条目。
  5. HashMap stores entries into multiple singly linked lists, called buckets or bins. Default number of bins is 16 and it’s always power of 2.

    HashMap将条目存储到多个单独链接的列表中,这些列表称为存储桶或存储箱。 默认箱数为16,始终为2的幂。
  6. HashMap uses hashCode() and equals() methods on keys for get and put operations. So HashMap key object should provide good implementation of these methods. This is the reason immutable classes are better suitable for keys, for example String and Interger.

    HashMap在键上使用hashCode()和equals()方法进行获取和放置操作。 因此,HashMap关键对象应提供这些方法的良好实现。 这就是不可变类更适合于键的原因,例如String和Interger。
  7. Java HashMap is not thread safe, for multithreaded environment you should use ConcurrentHashMap class or get synchronized map using Collections.synchronizedMap() method.

    Java HashMap不是线程安全的,对于多线程环境,应使用ConcurrentHashMap类或使用Collections.synchronizedMap()方法获取同步地图。

Java HashMap构造函数 (Java HashMap Constructors)

Java HashMap provides four constructors.

Java HashMap提供了四个构造函数。

  1. public HashMap(): Most commonly used HashMap constructor. This constructor will create an empty HashMap with default initial capacity 16 and load factor 0.75

    public HashMap() :最常用的HashMap构造函数。 此构造函数将创建一个空的HashMap,其默认初始容量为16,负载因子为0.75。
  2. public HashMap(int initialCapacity): This HashMap constructor is used to specify the initial capacity and 0.75 load factor. This is useful in avoiding rehashing if you know the number of mappings to be stored in the HashMap.

    public HashMap(int initialCapacity) :此HashMap构造函数用于指定初始容量和0.75负载系数。 如果您知道要在HashMap中存储的映射数,则这对于避免重新散列很有用。
  3. public HashMap(int initialCapacity, float loadFactor): This HashMap constructor will create an empty HashMap with specified initial capacity and load factor. You can use this if you know the maximum number of mappings to be stored in HashMap. In common scenarios you should avoid this because load factor 0.75 offers a good tradeoff between space and time cost.

    public HashMap(int initialCapacity,float loadFactor) :此HashMap构造函数将创建一个具有指定初始容量和负载因子的空HashMap。 如果您知道要在HashMap中存储的最大映射数,则可以使用此方法。 在常见情况下,应避免这种情况,因为负载系数0.75在空间和时间成本之间提供了很好的权衡。
  4. public HashMap(Map<? extends K, ? extends V> m): Creates a Map having same mappings as the specified map and with load factor 0.75

    public HashMap(Map <?扩展K,?扩展V> m) :创建一个与指定地图具有相同映射并且负载因子为0.75的Map

Java HashMap构造函数示例 (Java HashMap Constructors Example)

Below code snippet is showing HashMap example of using all the above constructors.

下面的代码片段显示了使用上述所有构造函数的HashMap示例。

Map<String, String> map1 = new HashMap<>();

Map<String, String> map2 = new HashMap<>(2^5);

Map<String, String> map3 = new HashMap<>(32,0.80f);

Map<String,String> map4 = new HashMap<>(map1);

Java HashMap方法 (Java HashMap Methods)

Let’s have a look at the important methods of HashMap in java.

让我们看一下Java中HashMap的重要方法。

  1. public void clear(): This HashMap method will remove all the mappings and HashMap will become empty.

    public void clear() :此HashMap方法将删除所有映射,并且HashMap将变为空。
  2. public boolean containsKey(Object key): This method returns ‘true’ if the key exists otherwise it will return ‘false’.

    public boolean containsKey(Object key) :如果密钥存在,则此方法返回“ true”,否则将返回“ false”。
  3. public boolean containsValue(Object value): This HashMap method returns true if the value exists otherwise false.

    public boolean containsValue(Object value) :如果值存在,则此HashMap方法返回true,否则返回false。
  4. public Set<Map.Entry<K,V>> entrySet(): This method returns a Set view of the HashMap mappings. This set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

    public Set <Map.Entry <K,V >> entrySet() :此方法返回HashMap映射的Set视图。 该集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。
  5. public V get(Object key): Returns the value mapped to the specified key, or null if there is no mapping for the key.

    public V get(Object key) :返回映射到指定键的值;如果没有该键的映射,则返回null。
  6. public boolean isEmpty(): A utility method returning true if no key-value mappings are present.

    public boolean isEmpty() :一种实用程序方法,如果不存在键值映射,则返回true。
  7. public Set<K> keySet(): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

    public Set <K> keySet() :返回此映射中包含的键的Set视图。 该集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。
  8. public V put(K key, V value): Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

    public V put(K key,V value) :将指定值与此映射中的指定键相关联。 如果该映射先前包含该键的映射,则将替换旧值。
  9. public void putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.

    public void putAll(Map <?扩展K,?扩展V> m) :将所有映射从指定映射复制到此映射。 这些映射将替换该映射对指定映射中当前存在的任何键的任何映射。
  10. public V remove(Object key): Removes the mapping for the specified key from this map if present.

    public V remove(Object key) :从此映射中删除指定键的映射(如果存在)。
  11. public int size(): Returns the number of key-value mappings in this map.

    public int size() :返回此映射中的键值映射数。
  12. public Collection<V> values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

    public Collection <V> values() :返回此映射中包含的值的Collection视图。 集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。

There are many new methods in HashMap introduced in Java 8.

Java 8中引入了HashMap中的许多新方法。

  1. public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction): If the specified key is not already associated with a value (or is mapped to null), this method attempts to compute its value using the given mapping function and enters it into the HashMap unless Null.

    public V computeIfAbsent(K key,Function <?super K,?extended V> mappingFunction) :如果指定的键尚未与值关联(或映射为null),则此方法尝试使用给定的映射来计算其值函数,除非Null,否则将其输入到HashMap中。
  2. public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction): If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

    public V computeIfPresent(K key,BiFunction <?super K,?super V,?extended V> remappingFunction) :如果指定键的值存在且非空,则尝试计算给定键及其当前值的新映射映射值。
  3. public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction): This HashMap method attempts to compute a mapping for the specified key and its current mapped value.

    公共V计算(K键,BiFunction <?super K,?super V ,?扩展V> remappingFunction) :此HashMap方法尝试计算指定键及其当前映射值的映射。
  4. public void forEach(BiConsumer<? super K, ? super V> action): This method performs the given action for each entry in this map.

    public void forEach(BiConsumer <?super K,?super V> action) :此方法对映射中的每个条目执行给定的操作。
  5. public V getOrDefault(Object key, V defaultValue): Same as get except that defaultValue is returned if no mapping found for the specified key.

    public V getOrDefault(Object key,V defaultValue) :与get相同,除了如果找不到指定键的映射关系,则返回defaultValue。
  6. public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction): If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.

    公共V merge(K键,V值,BiFunction <?super V,?super V,?extended V> remappingFunction) :如果指定键尚未与值关联或与null关联,则将其与给定的non关联-null值。 否则,用给定的重映射函数的结果替换关联的值,如果结果为null,则将其删除。
  7. public V putIfAbsent(K key, V value): If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

    public V putIfAbsent(K key,V value) :如果指定的键尚未与某个值关联(或映射为null),则将其与给定值关联并返回null,否则返回当前值。
  8. public boolean remove(Object key, Object value): Removes the entry for the specified key only if it is currently mapped to the specified value.

    public boolean remove(Object key,Object value) :仅当当前映射到指定值时,才删除指定键的条目。
  9. public boolean replace(K key, V oldValue, V newValue): Replaces the entry for the specified key only if currently mapped to the specified value.

    public boolean replace(K key,V oldValue,V newValue) :仅当当前映射到指定值时,才替换指定键的条目。
  10. public V replace(K key, V value): Replaces the entry for the specified key only if it is currently mapped to some value.

    public V replace(K key,V value) :仅当当前映射到某个值时,才替换指定键的条目。
  11. public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function): Replaces each entry’s value with the result of invoking the given function on that entry.

    public void replaceAll(BiFunction <?super K,?super V,?extends V> function) :用在该条目上调用给定函数的结果替换每个条目的值。

Java HashMap示例 (Java HashMap Example)

Here is a simple java program for HashMap commonly used methods.

这是用于HashMap常用方法的简单Java程序。

package com.journaldev.examples;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapExample {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<>();

		map.put("1", "1"); // put example
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", null); // null value
		map.put(null, "100"); // null key

		String value = map.get("3"); // get example
		System.out.println("Key = 3, Value = " + value);

		value = map.getOrDefault("5", "Default Value");
		System.out.println("Key = 5, Value=" + value);

		boolean keyExists = map.containsKey(null);
		boolean valueExists = map.containsValue("100");

		System.out.println("keyExists=" + keyExists + ", valueExists=" + valueExists);

		Set<Entry<String, String>> entrySet = map.entrySet();
		System.out.println(entrySet);

		System.out.println("map size=" + map.size());

		Map<String, String> map1 = new HashMap<>();
		map1.putAll(map);
		System.out.println("map1 mappings= " + map1);

		String nullKeyValue = map1.remove(null);
		System.out.println("map1 null key value = " + nullKeyValue);
		System.out.println("map1 after removing null key = " + map1);

		Set<String> keySet = map.keySet();
		System.out.println("map keys = " + keySet);

		Collection<String> values = map.values();
		System.out.println("map values = " + values);

		map.clear();
		System.out.println("map is empty=" + map.isEmpty());

	}

}

Below is the output of above Java HashMap example program.

以下是上述Java HashMap示例程序的输出。

Key = 3, Value = 3
Key = 5, Value=Default Value
keyExists=true, valueExists=true
[null=100, 1=1, 2=2, 3=3, 4=null]
map size=5
map1 mappings= {null=100, 1=1, 2=2, 3=3, 4=null}
map1 null key value = 100
map1 after removing null key = {1=1, 2=2, 3=3, 4=null}
map keys = [null, 1, 2, 3, 4]
map values = [100, 1, 2, 3, null]
map is empty=true

HashMap如何在Java中工作? (How HashMap works in java?)

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.

Java中的HashMap使用其内部类Node <K,V>来存储映射。 HashMap使用哈希算法,并在密钥上使用hashCode()和equals()方法进行获取和放置操作。

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.

HashMap使用单链表来存储元素,这些元素称为箱或桶。 当我们调用put方法时,键的hashCode用于确定将用于存储映射的存储桶。

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.

标识存储桶后,将使用hashCode来检查是否已经存在具有相同hashCode的密钥。 如果存在具有相同hashCode的键,则对键使用equals()方法。 如果equals返回true,则值将被覆盖,否则对该单链接列表存储桶进行新映射。 如果没有具有相同hashCode的键,则将映射插入到存储桶中。

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.

对于HashMap get操作,再次使用键hashCode来确定要查找值的存储桶。 标识存储桶后,使用hashCode和equals方法遍历条目以找出条目。 如果找到匹配项,则返回value,否则返回null。

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.

涉及更多的事情,例如散列算法以获取密钥的存储桶,重新映射的映射等。但是对于我们的工作,请记住,HashMap操作对Key起作用,并且hashCode的良好实现,并且equals方法是必需的,以避免不必要的行为。 下图显示了get和put操作的说明。

Recommended Read: hashCode and equals method importance in Java

推荐阅读hashCode和等于Java中方法的重要性

Java HashMap负载因子 (Java HashMap Load Factor)

Load Factor is used to figure out when HashMap will be rehashed and bucket size will be increased. Default value of bucket or capacity is 16 and load factor is 0.75. Threshold for rehashing is calculated by multiplying capacity and load factor. So default threshold value will be 12. So when the HashMap will have more than 12 mappings, it will be rehashed and number of bins will be increased to next of power 2 i.e 32. Note that HashMap capacity is always power of 2.

加载因子用于确定何时重新哈希哈希表和增加存储桶大小。 铲斗或容量的默认值为16,负载系数为0.75。 通过将容量和负载因子相乘来计算重新哈希的阈值。 因此,默认阈值将为12。因此,当HashMap具有超过12个映射时,它将被重新映射,并且bin的数量将增加到次幂2(即32)。请注意,HashMap的容量始终为2的幂。

Default load factor of 0.75 provides good tradeoff between space and time complexity. But you can set it to different values based on your requirement. If you want to save space, then you can increase it’s value to 0.80 or 0.90 but then get/put operations will take more time.

默认负载因子0.75提供了在空间和时间复杂度之间的良好折衷。 但是您可以根据需要将其设置为不同的值。 如果要节省空间,则可以将其值增加到0.80或0.90,但获取/放入操作将花费更多时间。

Java HashMap keySet (Java HashMap keySet)

Java HashMap keySet method returns the Set view of keys in the HashMap. This Set view is backed by HashMap and any changes in HashMap is reflected in Set and vice versa. Below is a simple program demonstrating HashMap keySet examples and what is the way to go if you want a keySet not backed by map.

Java HashMap keySet方法返回HashMap中的键的Set视图。 此Set视图由HashMap支持,并且HashMap中的任何更改都将反映在Set中,反之亦然。 下面是一个演示HashMap keySet示例的简单程序,以及如果希望keySet不由map支持的方法,该怎么办。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class HashMapKeySetExample {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");

		Set<String> keySet = map.keySet();
		System.out.println(keySet);

		map.put("4", "4");
		System.out.println(keySet); // keySet is backed by Map

		keySet.remove("1");
		System.out.println(map); // map is also modified

		keySet = new HashSet<>(map.keySet()); // copies the key to new Set
		map.put("5", "5");
		System.out.println(keySet); // keySet is not modified
	}

}

Output of the above program will make it clear that keySet is backed by map.

以上程序的输出将清楚表明keySet由map支持。

[1, 2, 3]
[1, 2, 3, 4]
{2=2, 3=3, 4=4}
[2, 3, 4]

Java HashMap值 (Java HashMap values)

Java HashMap values method returns a Collection view of the values in the Map. This collection is backed by HashMap, so any changes in HashMap will reflect in values collection and vice versa. A simple example below confirms this behaviour of HashMap values collection.

Java HashMap values方法返回Map中值的Collection视图。 此集合由HashMap支持,因此HashMap中的任何更改都将反映在值集合中,反之亦然。 下面的一个简单示例确认了HashMap值收集的这种行为。

package com.journaldev.examples;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class HashMapValuesExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", null);
		map.put("4", null);
		map.put(null, "100");

		Collection<String> values = map.values();
		System.out.println("map values = " + values);

		map.remove(null);
		System.out.println("map values after removing null key = " + values);

		map.put("5", "5");
		System.out.println("map values after put = " + values);

		System.out.println(map);
		values.remove("1"); // changing values collection
		System.out.println(map); // updates in map too

	}

}

Output of above program is below.

上面程序的输出如下。

map values = [100, 1, 2, null, null]
map values after removing null key = [1, 2, null, null]
map values after put = [1, 2, null, null, 5]
{1=1, 2=2, 3=null, 4=null, 5=5}
{2=2, 3=null, 4=null, 5=5}

Java HashMap entrySet (Java HashMap entrySet)

Java HashMap entrySet method returns the Set view of mappings. This entrySet is backed by HashMap, so any changes in map reflects in entry set and vice versa. Have a look at the below example program for HashMap entrySet example.

Java HashMap entrySet方法返回映射的Set视图。 此entrySet由HashMap支持,因此映射中的任何更改都会反映在条目集中,反之亦然。 看看下面的HashMap entrySet示例示例程序。

package com.journaldev.examples;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapEntrySetExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		Set<Entry<String,String>> entrySet = map.entrySet();
		Iterator<Entry<String, String>> iterator = entrySet.iterator();
		Entry<String, String> next = null;
		
		System.out.println("map before processing = "+map);
		System.out.println("entrySet before processing = "+entrySet);
		while(iterator.hasNext()){
			next = iterator.next();
			System.out.println("Processing on: "+next.getValue());
			if(next.getKey() == null) iterator.remove();
		}
		
		System.out.println("map after processing = "+map);
		System.out.println("entrySet after processing = "+entrySet);
		
		Entry<String, String> simpleEntry = new AbstractMap.SimpleEntry<String, String>("1","1");
		entrySet.remove(simpleEntry);
		System.out.println("map after removing Entry = "+map);
		System.out.println("entrySet after removing Entry = "+entrySet);
	}

}

Below is the output produced by above program.

以下是上述程序产生的输出。

map before processing = {null=100, 1=1, 2=null}
entrySet before processing = [null=100, 1=1, 2=null]
Processing on: 100
Processing on: 1
Processing on: null
map after processing = {1=1, 2=null}
entrySet after processing = [1=1, 2=null]
map after removing Entry = {2=null}
entrySet after removing Entry = [2=null]

Java HashMap putIfAbsent (Java HashMap putIfAbsent)

A simple example for HashMap putIfAbsent method introduced in Java 8.

Java 8中引入的HashMap putIfAbsent方法的简单示例。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;

public class HashMapPutIfAbsentExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		System.out.println("map before putIfAbsent = "+map);
		String value = map.putIfAbsent("1", "4");
		System.out.println("map after putIfAbsent = "+map);
		System.out.println("putIfAbsent returns: "+value);
		
		System.out.println("map before putIfAbsent = "+map);
		value = map.putIfAbsent("3", "3");
		System.out.println("map after putIfAbsent = "+map);
		System.out.println("putIfAbsent returns: "+value);
	}

}

Output of above program is;

以上程序的输出为:

map before putIfAbsent = {null=100, 1=1, 2=null}
map after putIfAbsent = {null=100, 1=1, 2=null}
putIfAbsent returns: 1
map before putIfAbsent = {null=100, 1=1, 2=null}
map after putIfAbsent = {null=100, 1=1, 2=null, 3=3}
putIfAbsent returns: null

Java HashMap forEach (Java HashMap forEach)

HashMap forEach method is introduced in Java 8. It’s a very useful method to perform the given action for each entry in the map until all entries have been processed or the action throws an exception.

HashMap forEach方法是Java 8中引入的。这是一种非常有用的方法,它可以对映射中的每个条目执行给定的操作,直到处理完所有条目或该操作引发异常为止。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public class HashMapForEachExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		BiConsumer<String, String> action = new MyBiConsumer();
		map.forEach(action);
		
		//lambda expression example
		System.out.println("\nHashMap forEach lambda example\n");
		map.forEach((k,v) -> {System.out.println("Key = "+k+", Value = "+v);});
	}

}

class MyBiConsumer implements BiConsumer<String, String> {

	@Override
	public void accept(String t, String u) {
		System.out.println("Key = " + t);
		System.out.println("Processing on value = " + u);
	}

}

Output of above HashMap forEach example program is;

上面的HashMap forEach示例程序的输出是;

Key = null
Processing on value = 100
Key = 1
Processing on value = 1
Key = 2
Processing on value = null

HashMap forEach lambda example

Key = null, Value = 100
Key = 1, Value = 1
Key = 2, Value = null

Java HashMap replaceAll (Java HashMap replaceAll)

HashMap replaceAll method can be used to replace each entry’s value with the result of invoking the given function on that entry. This method is added in Java 8 and we can use lambda expressions for this method argument.

HashMap replaceAll方法可用于在每个条目上调用给定函数的结果来替换每个条目的值。 此方法是在Java 8中添加的,我们可以为该方法参数使用lambda表达式。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class HashMapReplaceAllExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "100");

		System.out.println("map before replaceAll = " + map);
		BiFunction<String, String, String> function = new MyBiFunction();
		map.replaceAll(function);
		System.out.println("map after replaceAll = " + map);

		// replaceAll using lambda expressions
		map.replaceAll((k, v) -> {
			if (k != null) return k + v;
			else return v;});
		System.out.println("map after replaceAll lambda expression = " + map);

	}

}

class MyBiFunction implements BiFunction<String, String, String> {

	@Override
	public String apply(String t, String u) {
		if (t != null)
			return t + u;
		else
			return u;
	}

}

Output of above HashMap replaceAll program is;

以上HashMap replaceAll程序的输出为;

map before replaceAll = {null=100, 1=1, 2=2}
map after replaceAll = {null=100, 1=11, 2=22}
map after replaceAll lambda example = {null=100, 1=111, 2=222}

Java HashMap的computeIfAbsent (Java HashMap computeIfAbsent)

HashMap computeIfAbsent method computes the value only if key is not present in the map. After computing the value, it’s put in the map if it’s not null.

HashMap的computeIfAbsent方法仅在键不存在于映射中时才计算该值。 计算完值后,如果不为空,则将其放入映射中。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class HashMapComputeIfAbsent {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "10");
		map.put("2", "20");
		map.put(null, "100");

		Function<String, String> function = new MyFunction();
		map.computeIfAbsent("3", function); //key not present
		map.computeIfAbsent("2", function); //key already present
		
		//lambda way
		map.computeIfAbsent("4", v -> {return v;});
		map.computeIfAbsent("5", v -> {return null;}); //null value won't get inserted
		System.out.println(map);
	}

}

class MyFunction implements Function<String, String> {

	@Override
	public String apply(String t) {
		return t;
	}
	
}

Output of above program is;

以上程序的输出为:

{null=100, 1=10, 2=20, 3=3, 4=4}

Java HashMap的computeIfPresent (Java HashMap computeIfPresent)

Java HashMap computeIfPresent method recomputes the value if the specified key is present and value is not-null. If the function returns null, the mapping is removed.

如果指定的键存在且值不为null,则Java HashMap的computeIfPresent方法将重新计算该值。 如果函数返回null,则删除映射。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class HashMapComputeIfPresentExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "10");
		map.put("2", "20");
		map.put(null, "100");
		map.put("10", null);

		System.out.println("map before computeIfPresent = " + map);
		BiFunction<String, String, String> function = new MyBiFunction1();
		for (String key : map.keySet()) {
			map.computeIfPresent(key, function);
		}
		
		System.out.println("map after computeIfPresent = " + map);
		map.computeIfPresent("1", (k,v) -> {return null;}); // mapping will be removed
		System.out.println("map after computeIfPresent = " + map);

	}

}

class MyBiFunction1 implements BiFunction<String, String, String> {

	@Override
	public String apply(String t, String u) {
		return t + u;
	}

}

Output produced by HashMap computeIfPresent example is;

HashMap的computeIfPresent示例产生的输出是;

map before computeIfPresent = {null=100, 1=10, 2=20, 10=null}
map after computeIfPresent = {null=null100, 1=110, 2=220, 10=null}
map after computeIfPresent = {null=null100, 2=220, 10=null}

Java HashMap计算 (Java HashMap compute)

If you want to apply a function on all the mappings based on it’s key and value, then compute method should be used. If there is no mapping and this method is used, value will be null for compute function.

如果要基于函数的键和值在所有映射上应用函数,则应使用计算方法。 如果没有映射并且使用此方法,则计算功能的值将为null。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;

public class HashMapComputeExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "10");
		map.put("10", null);

		System.out.println("map before compute = "+map);
		for (String key : map.keySet()) {
			map.compute(key, (k,v) -> {return k+v;});
		}
		map.compute("5", (k,v) -> {return k+v;}); //key not present, v = null
		System.out.println("map after compute = "+map);
	}

}

Output of HashMap compute example is;

HashMap计算示例的输出为;

map before compute = {null=10, 1=1, 2=2, 10=null}
map after compute = {null=null10, 1=11, 2=22, 5=5null, 10=10null}

Java HashMap合并 (Java HashMap merge)

If the specified key is not present or is associated with null, then associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.

如果指定的键不存在或与null关联,则将其与给定的非null值关联。 否则,用给定的重映射函数的结果替换关联的值,如果结果为null,则将其删除。

package com.journaldev.examples;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapMergeExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "10");
		map.put("10", null);

		for (Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			//merge throws NullPointerException if key or value is null
			if(key != null && value != null) 
			map.merge(entry.getKey(), entry.getValue(), 
					(k, v) -> {return k + v;});
		}
		System.out.println(map);
		
		map.merge("5", "5", (k, v) -> {return k + v;}); // key not present
		System.out.println(map);
		
		map.merge("1", "1", (k, v) -> {return null;}); // method return null, so remove
		System.out.println(map);

	}

}

Output of above program is;

以上程序的输出为:

{null=10, 1=11, 2=22, 10=null}
{null=10, 1=11, 2=22, 5=5, 10=null}
{null=10, 2=22, 5=5, 10=null}

That’s all for HashMap in Java, I hope that nothing important is missed. Share it with others too if you liked it.

Java的HashMap就是这样,我希望不要错过任何重要的事情。 如果您喜欢,也可以与他人分享。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/11560/java-hashmap

java中hashmap

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值