JDK1.8 series articles
- New in JDK1.8 (1) : Lambda expressions
- New in JDK1.8 (2) : Optional
- JDK1.8 new feature (3) : Stream
- New in JDK1.8 (4) : Maps
- New JDK1.8 feature (5) : new date and time API
Maps does not support Streams. The Map interface itself does not have a stream() method. You can create specialized streams on mapped keys, values, or entries using map.keyset ().stream(), map.values().stream(), and map.entrySet ().stream(). In addition, MAPS supports a variety of new ways to perform common tasks.
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
Copy the code
The above code is explicitly checked by putIfAbsent to prevent us from writing null values. ForEach accepts a consumer to perform an action on each value of the map. This example shows how to calculate in a map:
map.computeIfPresent(3, (num, val) -> val + num);
map.get(3); // val33
map.computeIfPresent(9, (num, val) -> null);
map.containsKey(9); // false
map.computeIfAbsent(23, num -> "val" + num);
map.containsKey(23); // true
map.computeIfAbsent(3, num -> "bam");
map.get(3); // val33
Copy the code
Next, let’s see how to delete a key-value pair with key 3 and value val3:
map.remove(3, "val3");
map.get(3); // val33
map.remove(3, "val33");
map.get(3); // null
Copy the code
Another useful method:
map.getOrDefault(42, "not found"); // not found
Copy the code
It is also easier to merge elements of a Map:
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
map.get(9); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
map.get(9); // val9concat
Copy the code
What the Merge does is to insert the key name if it does not exist, and otherwise Merge the value corresponding to the original key and reinsert it into the map.
The public,
If you want to see my updated Java direction learning article in the first time, you can follow the public account ** [Lucas’s Coffee shop]. All learning articles public number first, please scan the code to pay attention to oh! Java8 new features learning videos please pay attention to the public number, private message [Java8] ** can be free unscripted access to learning videos.