【问题标题】:Put to map if absent in Groovy without Java 8如果在没有 Java 8 的 Groovy 中不存在,则放入映射
【发布时间】:2016-08-24 10:41:18
【问题描述】:

仅当键尚不存在时,我才需要将条目放入地图。对于 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]

是否可以使用一些 Groovy 功能​​来做到这一点,还是我需要手动完成?

【问题讨论】:

标签: dictionary groovy


【解决方案1】:

我刚刚发现这也可以:

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]

用原始条目覆盖默认条目就足够了。

【讨论】:

    【解决方案2】:

    您可以使用元编程自行开发:

    Map.metaClass.putIfAbsent = { otherMap ->
        otherMap.each { k, v ->
            if (! delegate.keySet().contains(k)) {
                delegate.put(k, v)
            }
        }
        delegate
    }
    
    def map = [a: 1, b: 2, c: 3]
    def newEntries = [a: 11, b: 22, d: 44]
    
    def result = map.putIfAbsent(newEntries)
    
    assert [a: 1, b: 2, c: 3, d: 44] == result
    

    【讨论】:

      【解决方案3】:

      @Michael Easter 的解决方案非常优雅,但您也可以只使用 Java 1.5 中引入的java.util.concurrent.ConcurrentHashMap,并提供putIfAbsent(K key, V value) 方法。因此,您可以将代码实现为:

      import java.util.concurrent.ConcurrentHashMap;
      def map = new ConcurrentHashMap([a: 1, b: 2, c: 3])
      
      [a: 11, b: 22, d: 44].each() { k,v ->
          map.putIfAbsent(k,v);
      }
      
      assert [a: 1, b: 2, c: 3, d: 44] == map;
      

      【讨论】:

      • 是的,很好 - 但是 ConcurrentHashMap 在内存中创建了很多 ConcurrentHashMap$SegmentConcurrentHashMap$HashEntry[]ReentrantLock$NonfairSync,对于如此简单的操作,它看起来有点矫枉过正:)
      【解决方案4】:

      还有 Groovy 的 Map.withDefault() 方法,它更灵活,但也可用于此目的。行为会有所不同,因为在第一次请求默认值之前,它们实际上并没有添加到地图中:

      def map = [a: 1, b: 2, c: 3]
      def newEntries = [a: 11, b: 22, d: 44]
      
      def result = map.withDefault { k -> newEntries[k] }
      
      assert result == map
      assert result != [a: 1, b: 2, c: 3, d: 44]
      assert newEntries.keySet().every { k -> result[k] == map[k] ?: newEntries[k] }
      assert result == [a: 1, b: 2, c: 3, d: 44]
      

      【讨论】:

        猜你喜欢
        • 2012-01-17
        • 2013-08-26
        • 1970-01-01
        • 2014-06-19
        • 2018-11-15
        • 2016-05-20
        • 2014-06-06
        • 2016-03-21
        • 2023-03-17
        相关资源
        最近更新 更多