Home > Mobile >  From a HashMap, how to remove k number of elements with the highest values(Java)?
From a HashMap, how to remove k number of elements with the highest values(Java)?

Time:12-05

myMap = {1=3, 2=2, 3=6, 4=8, 5=2, 6=1}

k = 3

so I'll delete the (3) highest map items with the highest values.

What can I do in Java so the map becomes?

myMap = {2=2, 5=2, 6=1}

I tried a for loop that iterates (3) times

and within it, a nested for loop that uses map.entry to get the max value and remove it. I keep getting an error.


     int k =3; // number of large value pairs to remove

 int max = Collections.max(myMap.values()); // find max value
   

 for(int i =0; i<k ;i  ) {  // iterate 3 times to delete (3) sets

    for (Map.Entry<Integer, Integer> entry : myMap.entrySet()) {
        Integer key = entry.getKey(); // find key associated with current largest value 
        Integer value = entry.getValue();// find largest value 
        if(value==max) { // test retrieved vale with max value 
            hMap.remove(key);// remove set from HashMap
        }
        max = Collections.max(myMap.values()); // find new maximum
    }      
 }

Error:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:XXXX)
    at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:XXXX)
    at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:XXXX)

CodePudding user response:

form jdk17 myMap.entrySet() -> hashMap's implements it will create a new EntryIterator() object,then will use super class HashIterator's constructors without arguments, When you use hashMap's put() or remove() method, modCount will 1,As a result HashIterator's nextNode() enter image description here

CodePudding user response:

Using for(element e : list) loops uses the iterator of the map's entry set. This iterator can only exist once at a time. The problem can be fixed by using a traditional for loop instead: for (int i = 0; i < myMap.entrySet().size(); i ) or similar.

  • Related