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]);
}
In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.
There is no other way to directly put the arrays into Map. You need to iterate through the every element of array and insert a key,value pair into a Map.
You cannot do it this way. Both t and a will have different hashCode() values because the the java. lang. Array.
To convert an array to a Map one should perform the following steps: Create a two-dimensional array of String items. Use toMap(Object[] array) method of ArrayUtils class to convert the given array into a Map.
I can't imagine that
for (int i=0; i < keys.length; i++) {
map.put(keys[i],values[i]);
}
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.
In my opinion you have already discovered a pretty straight forward approach to this problem.
HashMap<Integer, String> map = new HashMap <Integer, String>();
int[] keys = {1, 3, 5, 7, 9};
String[] values = {"turtles", "are", "better", "than", "llamas"};
for(int i = 0; i < keys.length; i++){
map.put(keys[i], values[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With