小编典典
映射中的值可能不是唯一的。但是,如果它们是(在您的情况下),则可以按照您在问题中所写的内容进行操作,并创建将其转换的通用方法:
private static Map invert(Map map) {
Map inv = new HashMap();
for (Entry entry : map.entrySet())
inv.put(entry.getValue(), entry.getKey());
return inv;
}
Java 8:
public static Map invert(Map map) {
return map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey));
}
用法示例:
public static void main(String[] args) {
Map map = new HashMap();
map.put("Hello", 0);
map.put("World!", 1);
Map inv = invert(map);
System.out.println(inv); // outputs something like "{0=Hello, 1=World!}"
}
旁注:该put(.., ..)方法将返回键的“旧”值。如果它不为null,则可能抛出new IllegalArgumentException("Map
values must be unique")或类似的东西。
2020-09-16