Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I go about avoiding the java.util.ConcurrentModificationException error in the following snippet?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading