This is a read-only archive. No new posts or registrations. Privacy Page
Software

Adding ArrayList to HashMap

2 min read

This thread's last reply is from . Advice, software, and links below may be out of date — treat specific steps and download links with caution.

Looking for the outcome? Ask AI

Hi all,

Just wanted to see if I can shorten the code to add a new ArrayList to a HashMap. This is what I currently have:

public void putStudent(Student newStudent) {
  ArrayList studentToAdd = new ArrayList();
  studentToAdd.add(newStudent);
  mySchools.put(newStudent.getName(), studentToAdd);
}

mySchool is a HashMap>. What I currently have works but I wanted to see if there's a more efficient way to accomplish this. Any ideas will be appreciated.
Haven't compiled it, but something like this may do the trick:
import java.util.Arrays;

…

mySchools.put(newStudent.getName(), new ArrayList(Arrays.asList(studentToAdd));

However, I can't quite see why you want a whole ArrayList as your key value, since it looks like that method will mean every entry in your map will contain a key which is an ArrayList of a single student. Is there any reason why your HashMap can't be of type HashMap?
Hi jpshortstuff, Thanks for taking a look at this. The example was not really that well thought of. The example I had in mind was for a HashMap(String, ArrayList) but got confused in making up a scenario :smack: Looking back at my original example it does look silly. Maybe a better one would have been String studentName (key) and ArrayList studentGrades (value). The thing that was confusing me the most is if it was possible to create a new ArrayList, invoke the ArrayList.add() to put whatever in the ArrayList then add it into the HashMap in one go.
Hi Overbooked,

OK, I wasn't aware that was just an example. Reading the example code I gave you again, I notice I gave you wrong impression. Here's what I meant to write:
import java.util.Arrays

public void putStudent(Student newStudent) {
  mySchools.put(newStudent.getName(), new ArrayList(Arrays.asList(newStudent)));
}

That will allow you to create the ArrayList and add the entry in one go. The asList() can take any number of values representing the entries you want to add to your list.

However, although this is one line of code, I expect it is probably less efficient than your current method, since it involves creating a List, then converting it to an ArrayList.

Hope that helps.
It looks like Arrays.asList() solves the puzzle. I was trying stuff like new ArrayList().add(newStudent) and couldn't get it to work :lol: Thanks jpshortstuff :notworthy:

Ask AI

AI can make mistakes. Check the cited posts. Archived advice can be out-of-date

Don't include personal information. Questions and selected public posts go to OpenAI. About Ask AI