First, initialize a map data

Map<String, String> map = new HashMap<String, String>(); Map. put("0", "mm "); Map. Put ("1", "cm "); Map. Put ("2", "decimeter "); The map. The put (" 3 ", "m");Copy the code

Expect to iterate over the map, printing keys or values, for example:

Key =0,value= mm Key =1,value= cm Key =2,value= decimeter Key =3,value= meterCopy the code
  1. This is the most common and, in most cases, the most desirable traversal

    Used when both key values are needed

	    for(Map.Entry<String, String> entry:map.entrySet()){
			System.out.println("key="+entry.getKey()+",value="+entry.getValue());
		}
Copy the code
  1. Iterate over keys or values in a for-each loop

    If you only need the keys or values in the map, you can traverse through keySet or values instead of entrySet. This method performs slightly better than entrySet traversal (10% faster) and the code is cleaner

For (String key: map.keyset ()){system.out.println ("key="+key); For (String value:map.values()){system.out.println ("value="+value); }Copy the code
  1. Iterator Iterator

    This approach looks redundant but has its advantages. First, in older versions of Java, this was the only way to traverse a map. Another benefit is that you can delete entries by calling iterator.remove() on a loop, whereas the other two methods cannot. According to javadoc, if you try to use this method in a for-each traversal, the results are unpredictable

    In terms of performance, this method is similar to the performance of for-each traversal (method two)

——– Use generics:

		Iterator<Entry<String, String>> entries = map.entrySet().iterator();
		while(entries.hasNext()){
			Entry<String, String> entry = entries.next();
			System.out.println("key="+entry.getKey()+",value="+entry.getValue());
		}
Copy the code

——– Not using generics:

		Iterator entries = map.entrySet().iterator();
		while(entries.hasNext()){
			Map.Entry entry = (Map.Entry)entries.next();
			String key = (String)entry.getKey();
			String value = (String)entry.getValue();
			System.out.println("key="+entry.getKey()+",value="+entry.getValue());
		}
Copy the code
  1. Traversal by key (inefficient)

    As an alternative to method one, this code looks cleaner; But it’s actually quite slow and inefficient. Because the value from the key is a time-consuming operation (20% to 200% slower in different Map implementations than in method one). So try to avoid it

		for(String key:map.keySet()){
			String value = map.get(key);
			System.out.println("key="+key+",value="+value);
		}
Copy the code