简体   繁体   English

如何使用 Guava Multimap 的 replaceValues 方法?

[英]How to use replaceValues method of Guava Multimap?

I want to add, remove and replace values in a MultiMap provided by Guava.我想在 Guava 提供的 MultiMap 中添加、删除和替换值。

I do this currently to add values..我目前这样做是为了增加价值..

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);

Removing values is easier with Guava library.使用 Guava 库可以更轻松地删除值。

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

But how can I use the replaceValues method?但是我怎样才能使用 replaceValues 方法呢?

I mean this我是说这个

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

Say I wanted to replace value 4.3 with a new value 5.99, how should I do that, the method expects some Iterable function and I am not sure as of how to implement it..假设我想用新值 5.99 替换值 4.3,我该怎么做,该方法需要一些 Iterable 函数,但我不确定如何实现它。

This is the error..这是错误..

The method replaceValues(Integer, Iterable) in the type Multimap is not applicable for the arguments (int, float) Multimap 类型中的方法 replaceValues(Integer, Iterable) 不适用于参数 (int, float)

Multimap.replaceValues takes a collection of values that replaces all of the existing values for the given key. Multimap.replaceValues采用一组值替换给定键的所有现有值。 From the JavaDoc it looks like you need to use remove followed by put .从 JavaDoc 看来,您需要使用remove后跟put

If the map is modifiable, you can get a modifiable view on the collection of values mapped to a single key using get , but the view returned is a plain Collection without an atomic replace method.如果映射是可修改的,您可以使用get映射到单个键的值集合的可修改视图,但返回的视图是没有原子替换方法的普通Collection You can always create your own helper method.您始终可以创建自己的辅助方法。 Note that this method is not thread-safe.请注意,此方法不是线程安全的。

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;
}
public class 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);
    }
}

// result : {book=[4, 3], game=[4, 3]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM