Good day. The question is how to remove elements from the
Map collection . I’m trying to solve another problem and I can’t move forward, because I don’t understand on what principle deletion from the collection occurs. The idea is to remove identical elements from a collection; the comparison is done by value. From the level 8 lectures I understood that "iterator" is something like a link to our collection. Therefore, I created 2 such links and, by comparing the elements in the collection, decided to delete the elements to which this link (object) iterator2 refers. Explain why I'm doing it wrong. I really want to understand where I'm wrong. Thanks to everyone who will respond. Another option for implementing removal from a collection
for (Iterator
> iterator1 = map.entrySet().iterator(); iterator1.hasNext();){ HashMap.Entry
pair1 = iterator1.next(); for (Iterator
> iterator2 = map.entrySet().iterator(); iterator2.hasNext();) { HashMap.Entry
pair2 = iterator2.next(); if(pair1.getValue().equals(pair2.getValue())){ map.remove(pair2.getKey()); } } }
Iterator
> iterator1 = map.entrySet().iterator(); while(iterator1.hasNext()){ Map.Entry
pair1 = iterator1.next(); Iterator
> iterator2 = map.entrySet().iterator(); while(iterator2.hasNext()){ Map.Entry
pair2 = iterator2.next(); if (pair1.getValue().equals(pair2.getValue())){ iterator2.remove(); } } }
GO TO FULL VERSION