本文介绍了我们有MultiBiMap吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我们现在,有BiMap和multiMap的概念,但有一个multiBiMap?那么我的意思是什么呢。
在multiMap中,你有K和V之间的一对多关系,一个关键字可以关联到多个值,因此也就是名字。
在bi图中,您有K,V双双向平均值,您也可以得到V,K关系。像有两个常规地图,但同步。我需要一个双向多图,将这两个概念结合起来。

解决方案
  import java.util.Set; 

import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;

公共类ManyToMany< K,V> {
private final SetMultimap< K,V> keysToValues = HashMultimap.create();

private final SetMultimap< V,K> valuesToKeys = HashMultimap.create();

public Set< V> getValues(K key){
return keysToValues.get(key);
}

public Set< K> getKeys(V值){
返回valuesToKeys.get(value);
}

public boolean put(K key,V value){
return keysToValues.put(key,value)&& valuesToKeys.put(value,key);
}

public boolean putAll(K key,Iterable< ;? extends V> values){
boolean changed = false;
for(V value:values){
changed = put(key,value)||改变;
}
返回已更改;
}
}


As we now, there is the concept of BiMap and multiMap but is there a multiBiMap ? so what do I mean by this. In multiMap you have one-to-many relationship between K and V, a single key can be associated to multiple value, hence the name. In bi map you have K,V pair which is bi-directional mean you can get V,K relationship as well. Like having a two regular maps but synchronized. I need a bi directional multi map where you combine these two concepts.

解决方案
import java.util.Set;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;

public class ManyToMany<K, V> {
    private final SetMultimap<K, V> keysToValues = HashMultimap.create();

    private final SetMultimap<V, K> valuesToKeys = HashMultimap.create();

    public Set<V> getValues(K key) {
        return keysToValues.get(key);
    }

    public Set<K> getKeys(V value) {
        return valuesToKeys.get(value);
    }

    public boolean put(K key, V value) {
        return keysToValues.put(key, value) && valuesToKeys.put(value, key);
    }

    public boolean putAll(K key, Iterable<? extends V> values) {
        boolean changed = false;
        for (V value : values) {
            changed = put(key, value) || changed;
        }
        return changed;
    }
}

这篇关于我们有MultiBiMap吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 06:12