Four methods of map traversal

Four methods of map traversal
public static void main(String[] args) {
  Map<String, String> map = new HashMap<String, String>();
  map.put("1", "value1");
  map.put("2", "value2");
  map.put("3", "value3");
  
  //The first type: commonly used, secondary value
  System.out.println("traverse key and value through Map.keySet: ");
  for (String key : map.keySet()) {
   System.out.println("key= "+ key + " and value= " + map.get(key));
  }
  
  //Second
  System.out.println("Use iterator to traverse key and value through Map.entrySet: ");
  Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
  while (it.hasNext()) {
   Map.Entry<String, String> entry = it.next();
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }
  
  //The third type: recommended, especially when the capacity is large
  System.out.println("traverse key and value through Map.entrySet");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }
  // fourth
  System.out.println("traverse all values ​​through Map.values(), but not traverse keys");
  for (String v : map.values()) {
   System.out.println("value= " + v);
  }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326524181&siteId=291194637