I'm having issues sorting out the ArrayList found inside of the hashmap, or treemap. the goal is to have the program print out the key, along with the sorted arraylist. I tried using Collections, but it didnt work, any help is welcome :)
public static void main(String[] args) {
ArrayList<StudentCourse> List = new ArrayList<StudentCourse>();
List.add(new StudentCourse(2, "MATH210"));
List.add(new StudentCourse(2, "CS105"));
List.add(new StudentCourse(1, "S300"));
List.add(new StudentCourse(1, "CS200"));
HashMap<Integer, ArrayList<String>> HMap = new HashMap<>();
for (StudentCourse st : List) {
if (HMap.containsKey(st.getStudentID())) {
HMap.get(st.getStudentID()).add(st.getCourse());
} else {
HMap.put(st.getStudentID(), new ArrayList<>());
HMap.get(st.getStudentID()).add(st.getCourse());
}
}
Collections.sort(List);//this leads to an error.
Map<Integer, ArrayList<String>> TrMap = new TreeMap<Integer, ArrayList<String>>(HMap);
System.out.println(TrMap.toString());
}
the output is this :
{1=[S300, CS200], 2=[MATH210, CS105]}
while the intent is to have the the arraylist sorted, so:
1=[cS200, S300], 2=[CS105, MATH210]
Collections.sort(list);and it's sorted (create a minimal reproducible example). Please stick to naming conventions, variable names should always start with lower case characters.Comparatorobject or to define a natural ordering on your custom elements (by lettingStudentCourseimplementComparable). Otherwise nobody knows howStudentCourseobjects should be sorted.