本篇介绍以键值对形式存储数据的结构HashMap。主要介绍它的4种遍历方式。
package com.example.javatest;//包名定义
/**
* Author:W
* Map
* HashMap:一个散列表,它存储的内容是键值对(key-value)映射。
*/
import java.util.*;
import java.util.HashMap;
public class MainTest {
public static void main(String[] args)
{
HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
hashMap.put(1,"TaoBao");
hashMap.put(2,"TikTok");
hashMap.put(3,"HuaWei");
hashMap.put(4,"XiaoMi");
System.out.println("hashMap的大小:"+hashMap.size());
System.out.println("访问hashMap的元素:"+hashMap.get(2));
System.out.println("删除hashMap的元素:"+hashMap.remove(4));
//遍历1
System.out.println("===通过key键来遍历散列表===");
for (Integer key : hashMap.keySet())
{
System.out.println("key= " + key + " value= " + hashMap.get(key));
}
//遍历2
System.out.println("===通过value来遍历散列表===");
for (String value : hashMap.values())
{
System.out.println(" value: " + value);
}
//遍历3
System.out.println("===通过HashMap.entrySet使用iterator遍历key和value===");
Iterator<HashMap.Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
HashMap.Entry<Integer, String> entry = iterator.next();
System.out.println("key= " + entry.getKey() + " value= " + entry.getValue());
}
//遍历4
System.out.println("===通过HashMap.entrySet遍历key和value===");
for (HashMap.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println("key= " + entry.getKey() + " value= " + entry.getValue());
}
}
}
运行结果如下: