Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputting Arrays into a Hashmap

Tags:

java

hashmap

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]);
}
like image 314
Matt Avatar asked Feb 19 '13 10:02

Matt


People also ask

Can you put an array in a HashMap?

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.

How do you input an array into a Map?

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.

Can we store array as key in HashMap?

You cannot do it this way. Both t and a will have different hashCode() values because the the java. lang. Array.

Can we convert array to Map in Java?

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.


2 Answers

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.

like image 189
Brian Agnew Avatar answered Sep 26 '22 01:09

Brian Agnew


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]);
}
like image 40
Kevin Bowersox Avatar answered Sep 26 '22 01:09

Kevin Bowersox