Should I use an iterator to create a loop over a HashMap?

I have HashMap<String,String>(called p2p), and I want to loop over its elements. I found the following simple way to do this:

for (String key : p2p.keySet()) {
   value = p2p.get(key);
}

However, later I found out what people use iterator(). For instance:

Iterator it = p2p.keySet().iterator();
while(it.hasNext()) {
    key = it.next();
    value = p2p.get(key);
}

For me, the first way looks simpler. So my question is why do people use the second way? Does it have some objective advantages or is it just a matter of taste and subjectivity of simplicity?

+3
source share
7 answers

- , ( , .)

, , - /:

for (Map.Entry<String, String> entry : p2p.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

, .

+8

( ) , , . Iterator.remove(). collection.remove() - ConcurrentModificationException.

(, ).

+2

EntrySet, , :

:

HashMap<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}
+1

, , ( ) :

  • " foreach" Java 5, , JVM, .
  • foreach ( ) , . , hasNext() , , -, ..

, , .

0

Java. .

0

:

  • .
  • - Iterator , hasNext(), .
0
source

If you need to iterate over the values, follow these steps:

for(String value: map.values(){
   ...
}

If you need to iterate over key-value pairs, follow these steps:

for(Map.Entry<String, String> entry: map.entrySet()){
   ... entry.getKey(); 
   ... entry.getValue();
}

Remember that you SHOULD use an explicit Iterator (instead of foreach) when you want to remove something from the collection during iteration.

0
source

Source: https://habr.com/ru/post/1779144/


All Articles