Do you know the new method added by java8 Map? Can you use it?

After the release of java8, several new methods have been added to the map class library. Using these new methods can more easily manipulate the data in the map

New methods include:

getOrDefault,forEach,compute,computeIfAbsent,computeIfPresent,merge,putIfAbsent,remove(key,value),replace,replaceAll

getOrDefault

The getOrDefault() method obtains the value corresponding to the specified key pair. If the key is not found, the set default value is returned.

Syntax:

hashmap.get(Object key, V defaultValue)

Parameter Description:

  • Key - key
  • defaultValue - the default value returned when the specified key does not exist in the mapping relationship

Return value:

Returns the value mapped to the key. If the given key cannot be found in the mapping relationship, the specified default value is returned.

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);

The way before java8

Map<String, Integer> map = new HashMap<>(4);
map.put("lisa", 1);
int lisaValue = 0;
if (map.containsKey("lisa")) {
    lisaValue = map.get("lisa");
}
System.out.println(lisaValue);

java8

// If the mapping with key as lisa exists, the corresponding value is returned; otherwise, the default value of - 1 is returned
Integer java8lisaValue = map.getOrDefault("lisa", -1);
// 1
System.out.println(java8lisaValue);
// If the mapping with key as adas exists, the corresponding value is returned; otherwise, the default value of - 999 is returned
Integer adasValue = map.getOrDefault("adas", -999);
// adas
System.out.println(adasValue);

forEach

foreach allows us to quickly traverse a map in a Lambda fashion

Syntax:

map.forEach(BiConsumer<K, V> action)

Parameter Description:

  • Biconsumer - a new functional interface provided by java8, we can define traversal consumption logic

Return value:

nothing

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);

The way before java8

This is the most efficient way to obtain key value pair information through Map traversal in the past, because each group of key value pairs only needs to be traversed once, but the writing method is relatively old

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "==" + entry.getValue());
}

java8

In fact, the bottom layer of the foreach of the Java 8 map still uses the entrySet, but the upper layer uses the BiConsumer functional interface, which simplifies the code we directly traverse.

 map.forEach((k, v) -> System.out.println(k + "=" + v));

The specific implementation is as follows:

compute

Attempts to calculate the mapping of the specified key and its current mapping value (null if there is no current mapping)

Formula:

map.compute(K key, BiFunction remappingFunction)

Parameter Description:

  • Key - key
  • remappingFunction - remapping function used to recalculate values

Return value

If the value corresponding to the key does not exist, it returns Null. If it does exist, it returns the value recalculated by the remappingFunction and saves it to the mapping set (if the recalculated value is Null, it will not be saved, and the mapping will be deleted from the mapping set).

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);

Operation before java8

private static Integer computeBefore(String key, Integer newValue) {
    Map<String, Integer> map = new LinkedHashMap<>(4);
    map.put("lisa", 1);
    map.put("jone", 2);
    map.put("selina", 3);
    Integer oldValue = map.get(key);
    if (newValue != null) {
        if (map.containsKey(key) && oldValue != null) {
            map.remove(key);
        }
        return null;
    } else {
        map.put(key, newValue);
        return newValue;
    }
}

java8 operation

Key exists in Map

// If the join key exists and the new value is not null, the value (v + 234) corresponding to the latest join will be returned and added to the map set
Integer joneNewValue = map.compute("jone", (k, v) -> v == null ? 0 : v + 234);
// joneNewValue:236
System.out.println("joneNewValue:" + joneNewValue);
// {lisa=1, jone=236, selina=3}
System.out.println(map);

System.out.println("================");
// If the join key exists and the new value is null, the value null corresponding to the latest join will be returned and the mapping will be deleted in the original set
Integer joneNewValue2 = map.compute("jone", (k, v) -> null);
// joneNewValue2:null
System.out.println("joneNewValue2:" + joneNewValue2);
// The key join is removed
// {lisa=1, selina=3}
System.out.println(map);

Key does not exist in Map

// If the asd key does not exist and the new value is not null, the value 111 corresponding to the latest asd will be returned and saved in the mapping set map
Integer asdNewValue = map.compute("asd", (k, v) -> 111);
// asdNewValue:111
System.out.println("asdNewValue:" + asdNewValue);
// {lisa=1, selina=3, asd=111}
System.out.println(map);

System.out.println("================");
// If the box key does not exist and the new value is null, null will be returned and will not be saved to the map set
Integer boxNewValue = map.compute("box", (k, v) -> null);
// boxNewValue:null
System.out.println("boxNewValue:" + boxNewValue);
// {lisa=1, selina=3, asd=111}
System.out.println(map);

computeIfAbsent

If the KEY Value pair (k,v) of the specified KEY does not exist, or the corresponding Value is empty, add the KEY Value pair to the mapping set (Map)

Syntax:

map.computeIfAbsent(K key, Function remappingFunction)

Parameter Description:

  • Key - key
  • remappingFunction - remapping function used to recalculate values

Return value:

If the value corresponding to the key does not exist, the recalculated value obtained by the remappingFunction is used and saved as the value of the key. Otherwise, value is returned.

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);
map.put("ddd", null);

Operation before java8

Integer lisaValue = map.get("adas");
if ( !map.containsKey("adas")|| map.get("adas") == null) {
    map.put("adas", 2345);
}

java8 operation

// If there is no key value pair with key adas in the original mapping set, and the value corresponding to the new key adas is not null (2345), it will be added to the map mapping set and the value will be returned
Integer adas = map.computeIfAbsent("adas", x -> 2345);
// 2345
System.out.println(adas);
// {lisa=1, jone=2, selina=3, ddd=null, adas=2345}
System.out.println(map);

System.out.println("--------------");

// If the original mapping set has no key value pair whose key is dml, and the value corresponding to the new key ml is null, the addition is ignored and null is returned
Integer dmlValue = map.computeIfAbsent("dml", x -> null);
// null
System.out.println(dmlValue);
// {lisa=1, jone=2, selina=3, ddd=null, adas=2345}
System.out.println(map);

System.out.println("--------------");
// The original mapping set has a Key value pair whose Key is ddd, but the value corresponding to ddd is empty. If we add a valid value to ddd again, the original Key value pair will be overwritten
Integer dddNewValue = map.computeIfAbsent("ddd", x -> 0);
// 0
System.out.println(dddNewValue);
// {lisa=1, jone=2, selina=3, ddd=0, adas=2345}
System.out.println(map);

computeIfPresent

If the mapping of the specified KEY exists and the Value is not null, replace the original Value of the specified KEY with the current Value and save it in the mapping set. If the current Value is null, the mapping of the specified KEY will be deleted

Syntax:

map.computeIfPresent(K key, BiFunction remappingFunction)

Parameter Description:

  • Key - key
  • remappingFunction - remapping function used to recalculate values

Return value:

If the value corresponding to the key does not exist, it returns null. If it does exist, it returns the value recalculated by the remappingFunction.

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);
map.put("ddd", null);

Operation before java8

if (map.get("selina") != null) {
    Integer oldValue = map.get("selina");
    Integer newValue = 1232312;
    if (newValue != null) {
        map.put("selina", newValue);
    } else {
        map.remove("selina");
    } 
}

java8

// There is a corresponding KEY in the original mapping set. If the original value is not null and the current value is not null, the original KEY value pair mapping will be overwritten
Integer selinaNewValue = map.computeIfPresent("selina", (k, v) -> 888999);
// 888999
System.out.println(selinaNewValue);
// {lisa=1, jone=2, selina=888999, ddd=null}
System.out.println(map);

System.out.println("-------------------");
// There is a corresponding KEY in the original mapping set. The original value is not null. Now the value is null, remove the corresponding KEY value pair
Integer selinaNewValue2 = map.computeIfPresent("selina", (k, v) -> null);
// null
System.out.println(selinaNewValue2);
// selina removed
System.out.println(map);

System.out.println("-------------------");
// There is a corresponding KEY in the original mapping set. The original value is null, but now the value is not null. No operation is performed on the original mapping set
Integer dddNewValue = map.computeIfPresent("ddd", (k, v) -> 2222222);
System.out.println(dddNewValue);
System.out.println(map);

System.out.println("-------------------");
// There is no corresponding KEY in the original mapping set, and now value is not null. No operation is performed on the original mapping set
Integer mqNewValue = map.computeIfPresent("mq", (k, v) -> -1);
System.out.println(mqNewValue);
System.out.println(map);

merge

The merge() method will first determine whether the specified KEY exists. If it does not exist, the KEY VALUE pair will be added to the hashMap. If it does exist, the KEY VALUE pair will be remapped according to logic (how to merge the old and new values of the same KEY)

Syntax:

map.merge(key, value, remappingFunction)

Parameter Description:

  • Key - key
  • Value - value
  • remappingFunction - remapping function used to recalculate values

Return value:

If the value corresponding to the key does not exist, the value is returned. If it does exist, the value recalculated by the remappingFunction is returned.

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);
map.put("ddd", null);

As we all know, if the KEY of Map is the same, the later inserted value will overwrite the new value

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);
// {lisa=1, jone=2, selina=3}
System.out.println(map);
map.put("lisa", 2);
// {lisa=2, jone=2, selina=3}
System.out.println(map);

Merge allows us to choose how to handle the same KEY value according to our own choice, which is similar to conflict merging (how to merge is up to us)

// Use old value
map.merge("lisa", 100, (oldValue, newValue) -> oldValue);

// Adopt new value
map.merge("lisa", 100, (oldValue, newValue) -> oldValue);

// Logical processing and merging of old and new values
map.merge("lisa", 100, (oldValue, newValue) -> oldValue + newValue);
  map.merge("lisa", 100, Integer::sum);

be careful:

java8 Stream Collectors. The tomap () method requires us to merge conflicts. Otherwise, if data with the same KEY or Value is null, the program will report an error!

User adas = new User("adas", 23);
User adas2 = new User("adas", 28);
User mlg = new User("mlg", 34);
ArrayList<User> list = new ArrayList<>();
list.add(adas);
list.add(adas2);
list.add(mlg);
Map<String, Integer> userMap = list.stream().collect(Collectors.toMap(User::getName, User::getValue));
System.out.println(userMap);

Prompt us that the key conflicts!

solve:

Map<String, Integer> userMap = list.stream()
        .filter(x->x.name!=null && x.value!=null)
        // Here, the old value is overwritten with the new value
        .collect(Collectors.toMap(User::getName, User::getValue,(oldValue,newValue)->newValue));
// {adas=28, mlg=34}
System.out.println(userMap);

putIfAbsent

The putIfAbsent() method will first determine whether the specified key exists. If it does not exist, the key / Value pair will be inserted into the mapping set and return null. If it exists, the original Value will be returned

Syntax:

map.putIfAbsent(K key, V value)

Parameter Description:

  • Key - key
  • Value - value

Return value:

If the specified key already exists in the Map, return the value corresponding to the key value. If the specified key does not exist in the Map, return null.

Note that if the specified key has been associated with a null value before, the method also returns null.

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);

Written before java8

Integer newValue = 222;
Integer joneValue = map.get("jone");
if (joneValue == null) {
    joneValue = map.put("lisa", newValue);
} else {
    joneValue = joneValue;
} 

java8

// If selina does not exist in the source mapping set, null is returned for insertion
Integer adasValue = map.putIfAbsent("adas", 1);
System.out.println(adasValue);
System.out.println(map);

System.out.println("----------");

// If selina exists in the source mapping set, the original value will be returned without inserting
Integer selinaValue = map.putIfAbsent("selina", 33333);
System.out.println(selinaValue);
System.out.println(map);

remove(key,value)

Only when the specified KEY and VALUE exist in the mapping set and are bound KEY VALUE pairs

Syntax:

map.remove(K key, V value)

Parameter Description:

  • Key - key
  • Value - value

Return value:

Only when the key value mapping exists and the two are bound, the data will be removed and returned true. Otherwise, it will be false

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);

demonstration

// lisa-2 has no mapping relationship because it will not be removed
map.remove("lisa", 2);
// {lisa=1}
System.out.println(map);

replace

The replace() method replaces the value corresponding to the specified key in the mapping set.

Syntax:

map.replace(K key, V oldValue, V newValue)

Parameter Description:

  • Key - key
  • oldValue - old value value
  • newValue - new value

Return value:

If the oldValue does not exist, replace the key with the value and return the old value corresponding to the key. If it exists, replace and return the old value.

If the KEY does not exist, no operation will be done and null will be returned

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);

demonstration

// key exists and the original value is not null
Integer lisaOldValue = map.replace("lisa", 333);
// Returns the old value 1
System.out.println(lisaOldValue);
// The value of lisa has been replaced {lisa=333, hobo=null}
System.out.println(map);

System.out.println("___________________");

// key exists and original value is null
Integer hoboOldValue = map.replace("hobo", -1);
// Return old value null
System.out.println(hoboOldValue);
// The value of hobo has been replaced {lisa=333, hobo=-1}
System.out.println(map);
System.out.println("___________________");

// key does not exist
Integer adasOldValue = map.replace("adas", -1);
// null
System.out.println(adasOldValue);
// Unchanged {lisa=333, hobo=-1}
System.out.println(map);

replaceAll

The replaceAll() method replaces all mapped values in the mapping set with the results of the given function

Syntax:

map.replaceAll(Bifunction<K, V> function)

**Note: * * HashMap is an object of HashMap class.

Parameter Description:

  • function - a functional interface instance that generates mapping pairs of functions

Return value:

None. Only the values in the mapping set will be replaced.

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);
map.put("qq", null);

demonstration

// Before replaceAll: {lisa=1, jone=2, selina=3, qq=null}
System.out.println("replaceAll before:" + map);
map.replaceAll((k, v) -> v == null ? -1 : v * 100);

// After replaceAll: {Lisa = 100, Jones = 200, Selina = 300, QQ = - 1}
System.out.println("replaceAll after:" + map);

values

The values() method returns a collection of all values in the map

Syntax:

hashmap.values()

Parameter Description:

  • nothing

Return value:

Returns the collection of all value values in the Map

Analog data:

Map<String, Integer> map = new LinkedHashMap<>(4);
map.put("lisa", 1);
map.put("jone", 2);
map.put("selina", 3);
map.put("qq", null);

demonstration

// [lisa, jone, selina, qq]
System.out.println(map.keySet());
// [1, 2, 3, null]
System.out.println(map.values());

Keywords: Java java8

Added by danlindley on Wed, 15 Dec 2021 17:19:35 +0200