进阶day04-Map集合的第二种遍历方式(键值对遍历)
This commit is contained in:
41
javaSE-day04/src/com/inmind/map01/MapDemo03.java
Normal file
41
javaSE-day04/src/com/inmind/map01/MapDemo03.java
Normal file
@@ -0,0 +1,41 @@
|
||||
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为String,V也为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());
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user