简体   繁体   中英

how to sort the array list in HashMap<Integer, ArrayList<String>>

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]

There is really not much to it. You just iterate all value entries and call some sort algorithm on it. For example the one provided by the Collections#sort ( documentation ) method. The method sorts inline so you don't have to re-add the values or anything, just call the method and your value entry will be sorted:

Probably the shortest code to realize this is

map.values().forEach(Collections::sort);

The values method returns a Set of all your values in the map. The forEach applies the given method to all entries.


If you are more familiar with regular loops:

for (ArrayList<String> value : map.values()) {
    Collections.sort(value);
}

The approach you have posted in your comments works too:

for (Entry<Integer, ArrayList<String>> entry : map.entrySet()) {
    Collections.sort(entry.getValue());
}

but it is unnecessary to pull the whole Entry (with key) out of the map, you only need the values. So consider using the map#values method instead of the map#entrySet .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM