Reputation: 13
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.swing.JOptionPane;
public class HashMapDemo {
public static double runProcess;
public static int ID = 0;
public static void processHashMap() {
HashMap < Integer, ArrayList < String >> students = new HashMap < > ();
List < String > arr = new ArrayList < > (100);
int x = 0;
while (ID != -1) {
String uData = JOptionPane.showInputDialog("Please enter your Student ID and Course Number (Seperated by a space) or enter -1 to view list: ");
String[] splitter = uData.split(" ");
ID = Integer.parseInt(splitter[0]);
arr.add(0, splitter[1]);
students.put(ID, (ArrayList < String > ) arr);
x++;
}
System.out.println(Arrays.asList(students));
}
public static void main(String[] args) {
processHashMap();
}
}
Output is: [{-1=[Test3, Test2, Test1, Test], 10=[Test3, Test2, Test1, Test], 11=[Test3, Test2, Test1, Test]}]
I'm trying to get it to be designated to each ID, such that if someone enters ID "10 Test" "10 Test2" "100 Test3" only 10 will be 10=[Test2, Test] and 100=[Test3]
Upvotes: 1
Views: 79
Reputation: 22384
You need to get the existing ArrayList
with the ID
from the HashMap
and then add
the new element to it as shown below (follow the comments):
String[] splitter = uData.split(" ");
ID = Integer.parseInt(splitter[0]);
ArrayList<String> studentsList = students.get(ID);//get the existing list from Map
if(studentsList == null) {//if no list for the ID, then create one
studentsList= new ArrayList<>();
}
studentsList.add(0, splitter[1]);//add to list
students.put(ID, studentsList);//put the list inside map
Upvotes: 2