java 如何使用具有非唯一值的番石榴进行地图反演?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3678601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:58:45  来源:igfitidea点击:

How to do map inversion with Guava with non-unique values?

javacollectionsguava

提问by lacroix1547

How can we do that with Guava? Notice the presence of List<K>in the return type since many keys can map to the same value in any normal map.

我们如何用番石榴做到这一点?请注意List<K>返回类型中的存在,因为许多键可以映射到任何法线映射中的相同值。

public static <K, V> Map<V, List<K>> inverse(Map<K, V> map){
    Map<V, List<K>> result = new LinkedHashMap<V, List<K>>();
    for (Map.Entry<K, V> entry : map.entrySet()) {
        if(!result.containsKey(entry.getValue())){
            result.put(entry.getValue(), new ArrayList<K>());                
        }
        result.get(entry.getValue()).add(entry.getKey());
    }        
    return result;        
}

BiMapseems to insist on the unicity of the values, but I don't have this luxury.

BiMap似乎坚持价值观的单一性,但我没有这种奢侈。

回答by ColinD

You can do this:

你可以这样做:

Map<K, V> map = ...;
ListMultimap<V, K> inverse = Multimaps.invertFrom(Multimaps.forMap(map), 
    ArrayListMultimap.<V,K>create());

Do note that pretty much any time you write Map<K, List<V>>or Map<K, Set<V>>or some such, a ListMultimap<K, V>or SetMultimap<K, V>is what you really want.

请注意,几乎任何时候您编写Map<K, List<V>>或编写Map<K, Set<V>>此类文件时, a ListMultimap<K, V>orSetMultimap<K, V>都是您真正想要的。

回答by Nathan Hughes

Use a Multimap instead, pick one that uses a list, like ArrayListMultimap, that will allow dupes.

改用 Multimap,选择一个使用列表的,比如 ArrayListMultimap,这将允许欺骗。

Also you don't have to write your own invert method, there's one provided in com.google.common.collect.Multimaps.

此外,您不必编写自己的 invert 方法,com.google.common.collect.Multimaps 中提供了一个方法。

回答by Tomasz Linkowski

In case someone stumbles here now (well within Java's Streamera), here are two single-expression Stream-based solutions:

万一有人现在在这里绊倒(在 JavaStream时代),这里有两个Stream基于单表达式的解决方案:

1) Immutable version based on ImmutableListMultimap+ toImmutableListMultimapcollector

1)基于ImmutableListMultimap+toImmutableListMultimap收集器的不可变版本

ImmutableListMultimap<V, K> output = inputMap.entrySet().stream()
        .collect(ImmutableListMultimap.toImmutableListMultimap(Map.Entry::getValue, Map.Entry::getKey));

2) Mutable version based on ArrayListMultimap+ Multimaps.toMultimapcollector

2)基于ArrayListMultimap+Multimaps.toMultimap收集器的可变版本

ListMultimap<V, K> output = inputMap.entrySet().stream()
        .collect(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, ArrayListMultimap::create));