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

来源:互联网 发布:java开发工程师培训 编辑:程序博客网 时间:2024/05/22 09:25

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<String, String> hashMap = new HashMap<String, String>();
  hashMap.put("keya", "valueA");
  hashMap.put("keyb", "valueB");
  hashMap.put("keyc", "valueC");

  Set<Map.Entry<String, String>> setAll = hashMap.entrySet();
  Set<String> setKey = hashMap.keySet();
  Collection<String> collValue = hashMap.values();

  Iterator<Map.Entry<String, String>> itAll = setAll.iterator();
  Iterator<String> itKey = setKey.iterator();
  Iterator<String> itValue = collValue.iterator();
  
  System.out.println("HashMap的健值输出:");
  while (itAll.hasNext()) {
   Map.Entry<String, String> entry = (Map.Entry<String, String>) 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);
  }
 }
}

原创粉丝点击