HashMap的键值以及键和值的遍历(TreeMap同)

import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class HashMapTest {
 public static void main(String[] args) {
  Map hashMap = new HashMap();
  hashMap.put("keya", "valueA");
  hashMap.put("keyb", "valueB");
  hashMap.put("keyc", "valueC");

  Set> setAll = hashMap.entrySet();
  Set setKey = hashMap.keySet();
  Collection collValue = hashMap.values();

  Iterator> itAll = setAll.iterator();
  Iterator itKey = setKey.iterator();
  Iterator itValue = collValue.iterator();
  
  System.out.println("HashMap的健值输出:");
  while (itAll.hasNext()) {
   Map.Entry entry = (Map.Entry) itAll
     .next();
   String key = entry.getKey().toString();
   String value = entry.getValue().toString();
   System.out.println(key + "-->" + value);
  }
  System.out.println("HashMap的健输出:");
  while (itKey.hasNext()) {
   String key = itKey.next().toString();
   System.out.println(key);
  }
  System.out.println("HashMap的值输出:");
  while (itValue.hasNext()) {
   String key = itValue.next().toString();
   System.out.println(key);
  }
 }
}

你可能感兴趣的:(Java基础)