answersLogoWhite

0

Unfortunately, there seems to be no built in way of adding all elements of a list to a map. This means that we need to iterate through each element of the ArrayList and add it to the HashMap individually.

/**
* Generic method to add all elements from source into dest.
*/
public static final void addAll(final ArrayList source, final HashMap dest) {

// Iterate through each element in source and put it in dest.
for (int i = 0; i < source.size(); ++i) {

// We will use the index of each element of source as the key in dest.
dest.put(i, source.get(i));

}

}

Sample use:

// Create a new ArrayList and add some stuff to it.
ArrayList list = new ArrayList();
list.add(1); list.add(2); list.add(3);
list.add(4); list.add(5); list.add(6);
list.add(7); list.add(8); list.add(9);

// Print out our list
System.out.println(list);

// Create a new map and call our function
HashMap map = new HashMap();
addAll(list, map);

// Print out to verify identical contents
System.out.println(map);

User Avatar

Wiki User

15y ago

Still curious? Ask our experts.

Chat with our AI personalities

BeauBeau
You're doing better than you think!
Chat with Beau
RafaRafa
There's no fun in playing it safe. Why not try something a little unhinged?
Chat with Rafa
CoachCoach
Success isn't just about winning—it's about vision, patience, and playing the long game.
Chat with Coach

Add your answer:

Earn +20 pts
Q: How do you convert an ArrayList to a HashMap?
Write your answer...
Submit
Still have questions?
magnify glass
imp