I feel like this is a very simple question, but I couldn’t find an answer.
Can you input an array object to the put method of a HashMap?
Example:
Say you have a HashMap:
HashMap<Integer, String> map = new HashMap <Integer, String>();
You have an array of integers and an array of strings conveniently given. The arrays are not initialized as shown below, but contain unknown values (this is just easier for illustrating the result).
int[] keys = {1, 3, 5, 7, 9};
String[] values = {"turtles", "are", "better", "than", "llamas"};
I want the key-value pairs of the HashMap to be:
1, turtles
3, are
5, better
7, than
9, llamas
Can this be achieved with something like map.put(keys, values)? I know this doesn’t work, you should get an error like “The method put(Integer, String) in the type HashMap is not applicable for the arguments (int[], String[])“. I just want something more efficient, elegant, or compact than:
for (int i=0; i < keys.length; i++) {
map.put(keys[i],values[i]);
}
I can’t imagine that
could be made much more efficient. If it’s the sort of thing you’re going to do often then I’d perhaps write a helper object around
Map.Note that Map.putAll() exists if the values you want to add are already in a map.