1
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]

2
  • 2
    Create a new ArrayList for each student inside the loop. It seems you are reusing and appending to the same arraylist. Commented May 4, 2017 at 21:29
  • this is pretty much the solution for you Commented May 4, 2017 at 21:34

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.