dac*_*cwe 37
地图中的值可能不是唯一的.但是如果它们(在你的情况下)你可以按照你在问题中写的那样做,并创建一个通用方法来转换它:
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;
}
Run Code Online (Sandbox Code Playgroud)
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));
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
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!}"
}
Run Code Online (Sandbox Code Playgroud)
旁注:该put(.., ..)方法将返回键的"旧"值.如果它不是null,你可以扔一个new IllegalArgumentException("Map values must be unique")或类似的东西.
Rha*_*aun 10
用法示例
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
Map<String, Integer> inverted = HashBiMap.create(map).inverse();
Run Code Online (Sandbox Code Playgroud)
要在Java 8中获取给定映射的倒排形式:
public static <K, V> Map<V, K> inverseMap(Map<K, V> sourceMap) {
return sourceMap.entrySet().stream().collect(
Collectors.toMap(Entry::getValue, Entry::getKey,
(a, b) -> a) //if sourceMap has duplicate values, keep only first
);
}
Run Code Online (Sandbox Code Playgroud)
用法示例
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
Map<String, Integer> inverted = inverseMap(map);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25263 次 |
| 最近记录: |