Java 8 – 如何减少此地图操作的大小(行数)?

huangapple go评论103阅读模式
英文:

Java 8 - How to reduce the size (lines) of this map operation?

问题

Map<String, Map<String, String>> map = new HashMap<>();
map.computeIfAbsent(key_1, k -> new HashMap<>()).put(key_2, value);
英文:

I need to get value map for a key, if its not there create new map and insert the key/value. How can i reduce the number of lines of this operation using java 8 ?

Map&lt;String, Map&lt;String, String&gt; map = new HashMap();
Map&lt;String, String&gt; valueMap = map.get(key_1);
if(valueMap == null) {
	valueMap = new HashMap();
} 
valueMap.put(key_2, value);
map.put(key_1, valueMap);

答案1

得分: 3

你可以使用 Map 的 computeIfAbsent 方法查看文档

map.computeIfAbsent(key_1, k -> new HashMap<>()).put(key_2, value);

需要注意的是,不需要创建一个新的 HashMap 实例(与例如 getOrDefault 方法不同),如果存在一个键,只有在没有键时才需要创建(对应于你的示例中的 if(valueMap == null))。

英文:

You can use computeIfAbsent method of Map See The Documentation

map.computeIfAbsent(key_1, k -&gt; new HashMap&lt;&gt;()).put(key_2, value);

Note that you won't need to create a new HashMap instance (unlike getOrDefault method for example), if there is a key, only if there is nothing (corresponds to if(valueMap == null) in your example.

答案2

得分: 2

看一下 Map 的文档:https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

似乎 computeIfAbsent 是你想要的方法。

首先,声明一个函数 newMap(),它只需返回一个 new HashMap()。然后:

Map<String, Map<String, String>> map = new HashMap();
map.computeIfAbsent(key_1, k -> new HashMap<>());
map.get(key_1).put(key_2, value);

编辑:与其声明一个命名函数 newMap,你可以使用匿名函数 k -> new HashMap<>(),正如Mark Bramnik的回答中所建议的。

不要使用 .putIfAbsent(key_1, new HashMap()),或者 .getOrDefault,或者任何其他非惰性函数,即使默认值不需要被评估。这些函数适用于默认值是简单值的情况,例如 int;如果默认值需要调用 new 来构建,则不适用。

英文:

Looking at the documentation for Map: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

It looks like computeIfAbsent does what you want.

First, declare a function newMap() that simply returns a new HashMap(). Then:

Map&lt;String, Map&lt;String, String&gt; map = new HashMap();
map.computeIfAbsent(key_1, newMap);
map.get(key_1).put(key_2, value);

EDIT: Rather than declaring a named function newMap, you can use an anonymous function k -&gt; new HashMap&lt;&gt;(), as suggested in Mark Bramnik's answer.

Do not use .putIfAbsent(key_1, new HashMap()), or .getOrDefault, or any other non-lazy function that would evaluate its default value even if the default value is not needed. These functions are appropriate if the default value is a simple value, for instance an int; they are not appropriate if the default value requires a call to new to be built.

huangapple
  • 本文由 发表于 2020年9月11日 20:04:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63846739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定