Suppose we want to delete some items from a map based on indices, which is passed as an array. We can’t delete them by iterating through the array, because each time when we delete an item, the hash map shrinks by one. So the new index will be different from what we expect. We can use the following code to perform the operation without any delays.
public void deleteItemFromMap(String[] indexArray){
List beanList = getMap();
MyBean myBean = null;
int index = 0;
int newIndex;
if(indexArray!=null){
for (String indexString : indexArray) {
newIndex = Integer.parseInt(indexString) – index;
myBean = beanList.remove(newIndex);
if(null != myBean){
index = index + 1;
}
}
}
}