I am attempting to sort student scores from greatest to least and plan to accomplish this by iterating through each item in a HashMap that contains the student name and score, outputting the greatest one, then removing it from the HashMap and repeating until there are no scores left. I understand why I’m getting the ConcurrentModificationException, but am wondering if there is an easy way around it.
// calculates, formats, and outputs scores
public static void sort (final HashMap<String, Integer> students) {
for (String i : students.keySet()) {
System.out.println("key: " + i + " value: " + students.get(i));
}
for (String i : students.keySet()) {
final String key = Collections.max(students.entrySet(),
Map.Entry.comparingByValue()).getKey();
System.out.println(key + " " + students.get(key));
students.remove(key);
}
}
>Solution :
Why modify the map at all? Sort the entries by value, then output the data
public static void main(String[] args) {
sort(Map.of("mary", 4, "jane", 2, ".", 0));
}
public static void sort(final Map<String, Integer> students) {
for (final Map.Entry<String, Integer> entry : students.entrySet()) {
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
students.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));
}
This will also ensure that an efficient sorting algorithm is used.