2012-04-16 2 views
2

구아바가 제공 한 멀티 맵에서 값을 추가, 제거 및 바꾸기를 원합니다.Guava Multimap의 replaceValues ​​메소드를 사용하는 방법?

내가 값을 제거하면 구아바 라이브러리를 쉽게

static Multimap<Integer, Float> myMultimap; 
myMultimap = ArrayListMultimap.create(); 
myMultimap.put(1, (float)4.3); 
myMultimap.put(2, (float)4.9); 
myMultimap.put(1, (float)4.7); 
myMultimap.put(1, (float)4.5); 

..이 현재 값을 추가 할.

myMultimap.remove(1,(float)4.7); 

그러나 replaceValues ​​메소드는 어떻게 사용할 수 있습니까?

나는이

myMultimap.replaceValues(1, (float)4.3); 

나는 새 값 5.99로 값 4.3을 대체하고 싶어 말을 의미 어떻게 방법이 몇 가지의 Iterable 기능을 기대하고 내가 그것을 구현하는 방법으로 확실하지 않다, 그렇게해야 ..

이는 에러이다 ..

Multimap과는 인수에 적용하지 않은 유형의 방법 replaceValues ​​(정수의 Iterable에게) (INT, 플로트)

답변

4

Multimap.replaceValues 지정된 키의 기존 값 모든을 대체 값 컬렉션을합니다. JavaDoc에서 remove 다음에 put을 사용해야하는 것 같습니다.

지도가 수정 가능한 경우 get을 사용하여 단일 키에 매핑 된 값 컬렉션에 대한 수정 가능한보기를 가져올 수 있지만 반환되는보기는 원자 대체 방법이없는 일반 Collection입니다. 언제든지 자신 만의 도우미 메서드를 만들 수 있습니다. 이 메서드는 스레드로부터 안전하지 않습니다.

public static <K,V> boolean replaceValue(Multimap<K,V> map, K key, V oldValue, V newValue) { 
    if (map.remove(key, oldValue)) { 
     map.put(key, newValue); 
     return true; 
    } 
    return false; 
} 
+0

, 감사합니다 이제는 모두 이해가됩니다 ... 멀티 맵에서 값을 대체 할 방법이 있습니까? –

+1

@mirroredAbstraction - 만 키에 매핑 된 모든 값 - 한 번에하지 하나. –

+1

'ListMultimap' 또는'SetMultimap'하는'List' 또는'Set'를 각각 반환 get''Multimap과 번호를 사용하는 경우 : http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained# 멀티 맵 –

0

공용 클래스 guava_main {

public static void main(String[] args) { 
    // TODO Auto-generated method stub 

    Multimap map = HashMultimap.create(); 

    map.put("game", 1); 
    map.put("game", 2); 

    map.put("book", 4); 
    map.put("book", 3); 

    Iterable iter = map.get("book"); 
    map.replaceValues("game", iter); 

    System.out.println(map); 
} 

}

// 결과 : {책 = [4, 3, 게임 = [4, 3}

관련 문제