Language: JavaScript
Create a public class called Inverter with a single class method named invert. invert should accept a Map<String, Integer> and return a Map<Integer, String> with all of the key-value pairs swapped. You can assert that the passed map is not null.
Because values are not necessarily unique in a map, normally you would need a way to determine what the right approach is when two keys map to the same value. However, the maps passed to your function will not have any duplicate values.
Below is my current code.
import java.util.Map;
public class Inverter {
public static Map<Integer, String> invert(Map<String,
Integer> map) {
assert(!(map.equals(null)));
}
}
Implementation of Class with
Method with Map as arguments and to get return type as Map with key
pair being Swapped
As per Map Interface, Keys will be unique but not the values. We can make use of HashMap for storing two keys to store up the same value. Following up on the assertion technique to check NULL arguments, the below code results with Map with key pair being swapped.
The below invert method handles the
duplicate issue while swapping the Map key pair values using the
Merge function where the values can be replace or we can maintain
with the old value itself.
public static class Inverter {
public Map<Integer, String> invert(Map<String, Integer> map) {
assert(!(map.equals(null)));
Map<Integer, String> invertedMap = new HashMap<>();
invertedMap = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (oldValue, newValue) -> newValue));
System.out.println("Inverted Map :: " + invertedMap);
return invertedMap;
}
}
Get Answers For Free
Most questions answered within 1 hours.