问题描述
我需要创建逆映射 - 选择唯一值并为它们找到键.似乎唯一的方法是迭代所有键/值对,因为 entrySet 返回一组不唯一的值?谢谢.
I need create inverse map - select unique values and for them find keys.Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not unique?Thanks.
推荐答案
地图中的值可能不是唯一的.但是,如果它们是(在您的情况下),您可以按照您在问题中所写的那样做,并创建一个通用方法来转换它:
The values in a map may not be unique. But if they are (in your case) you can do as you wrote in your question and create a generic method to convert it:
private static <V, K> Map<V, K> invert(Map<K, V> map) {
Map<V, K> inv = new HashMap<V, K>();
for (Entry<K, V> entry : map.entrySet())
inv.put(entry.getValue(), entry.getKey());
return inv;
}
Java 8:
public static <V, K> Map<V, K> invert(Map<K, V> map) {
return map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey));
}
用法示例:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Hello", 0);
map.put("World!", 1);
Map<Integer, String> inv = invert(map);
System.out.println(inv); // outputs something like "{0=Hello, 1=World!}"
}
旁注:put(.., ..)
方法将返回键的旧"值.如果它不为空,您可能会抛出一个 new IllegalArgumentException("Map values must be unique")
或类似的东西.
Side note: the put(.., ..)
method will return the the "old" value for a key. If it is not null you may throw a new IllegalArgumentException("Map values must be unique")
or something like that.
这篇关于Java反转图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!