2016-08-24 6 views
0

キーがまだ存在しない場合にのみ、マップにエントリを入れる必要があります。 Javaの8で、私はちょうどputIfAbsentを使用したいが、私は、Java 7で問題を説明JavaなしでGroovyに存在しない場合はマップする8

コードの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の機能を利用することが可能ですか私はをそれを手動で行う必要がありますか?

+0

はそれが重複していないです:http://stackoverflow.com/questions/15640525/how-do-i-add-multiple-groovy-map-entries-over-without-over-current-entries? – Opal

+0

いいえ、私は 'Multimap'を必要としません、' HashMap'は私の問題では問題ありません –

答えて

1

あなたは、メタプログラミングで独自のロールできます

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 
5

私はちょうどこれが同様に動作することを考え出した:

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] 

これは、元のものとデフォルトのエントリを上書きするだけで十分です。

1

@Michael Easterのソリューションは非常にエレガントですが、java.util.concurrent.ConcurrentHashMapをJava 1.5で導入して使用することもでき、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; 
+0

しかし、 'ConcurrentHashMap'は' ConcurrentHashMap $ Segment'、 'ConcurrentHashMap $ HashEntry []'、 'ReentrantLock $ NonfairSync'をメモリに入れてしまいます。 –

1

もかなりより柔軟であるが、この目的のために使用することができ、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] 
関連する問題