1.使用迭代器输出HashMap中的value值
首先我们调用集合的values()方法,这个方法返回集合类型的对象。
然后这个对象调用iterator()方法。
最后使用Iterator引用指向上一步返回的结果
package cn.hpu.set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class DictionaryDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Mapmap=new HashMap();
//向该集合中添加元素
System.out.println("请输入三组单词对应的原单词和注释");
Scanner sc=new Scanner(System.in);
int i=0;
while(i<3) {
System.out.println("请输入单词(key)值");
String key=sc.next();
System.out.println("请输入解释(value)");
String value=sc.next();
map.put(key, value);
i++;
}
System.out.println("=============================");
//打印出value的值,直接使用迭代器
System.out.println("使用迭代器输出所有value的值");
Iterator it=map.values().iterator();
while(it.hasNext()) {
System.out.print(it.next()+"-");
}
System.out.println();
System.out.println("============================");
//使用entrySet方法获取key-value值
Set> set=map.entrySet();
for(Entryentry:set) {
System.out.print(entry.getKey()+"-");
System.out.println(entry.getValue());
}
}
}
2.使用Entry<>对象是获取集合中的所有键值对对象。然后将Entry对象用set集合存储。
使用增强型for循环将输出。
for(Entryentry:set) {
System.out.print(entry.getKey()+"-");
System.out.println(entry.getValue());
}
增强型for循环循环体的内容: for(对象类型 对象名:对象从哪获取)