Files
javaSE-0113/javaSE-day04/src/com/inmind/map01/MapDemo03.java

42 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind.map01;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*
键值对遍历
- public Set<Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。
*/
public class MapDemo03 {
public static void main(String[] args) {
//创建一个双列集合K为StringV也为String
Map<String, String> map = new HashMap<>();
//添加一对数据(增加)
map.put("刘备", "孙尚香");
map.put("吕布", "貂蝉");
map.put("董卓", "貂蝉");
System.out.println(map);
//直接获取双列集合所有的键值对对象
Set<Entry<String, String>> entries = map.entrySet();
//迭代器遍历键值对
Iterator<Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey()+"-"+entry.getValue());
}
System.out.println("-------------------------------------");
//foreach遍历键值对
for (Entry<String, String> entry : entries) {
System.out.println(entry.getKey()+"-"+entry.getValue());
}
}
}