我只需要在键不存在的情况下将条目放入地图.使用Java 8我只是使用putIfAbsent,但我在Java 7中使用Groovy.
代码说明问题:
def map = [a: 1, b: 2, c: 3]
def newEntries = [a: 11, b: 22, d: 44]
def result = // put new entries to the map only if they are not present
assert result == [a: 1, b: 2, c: 3, d: 44]
Run Code Online (Sandbox Code Playgroud)
是否可以使用一些Groovy功能来执行此操作,还是需要手动执行?
我刚才发现这也有效:
def map = [a: 1, b: 2, c: 3]
def newEntries = [a: 11, b: 22, d: 44]
def result = newEntries + map
assert result == [a: 1, b: 2, c: 3, d: 44]
Run Code Online (Sandbox Code Playgroud)
使用原始条目覆盖默认条目就足够了.