遍历map集合示例展示:
package map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
/**
* 问题:如何遍历map集合呢?
* @author superdrew
* Map key -- values
* 使用集合存储分数,课程,学生( list,set Collection)
* 使用 Map 存储 学生 ,根据id 查找学生 (快速的找到学生, 通过键 找到 值 学号--学生)
*
* 功能:使用map存储国家 名称
* 掌握 map的使用
*
* 总结:map如何遍历
* map不能直接遍历,转成set后在遍历
* 1.先得到所有的key 根据key再获取值
* 2.先得到所有的key和value 再从每一个key value中分别取出key 和 value
* 3.先得到entrySet(返回值是Set) 再交给Iterator迭代器
*
* map其它的一些方法
* map.remove("cn") 删除key 和 value 如果key不存在,返回null
* map.clear() 清空当前map中所有的key 和value
* map.isEmpty() 判断当前map是否为空
* map.containsKey("123") 判断当前map是否包涵这个key 如果不存在 返回false
* containsValue("Japan") 判断当前map是否包涵这个value 如果不存在 返回false
*
*
*/
public class TestMap2 {
public static void main(String[] args) {
//创建map集合
Map<String,String> map = new TreeMap<String,String>();
//往map集合添加 key 和 value
map.put("cn", "Chinese");
map.put("us", "America");
map.put("en", "England");
map.put("jp", "Japan");
map.put("us", "the united stas");
map.put("uk", "Japan");
map.put("cs", "cs");
System.out.println(map); //显示:初始map集合
System.out.println(map.remove("cn")); //通过键key="cn",来删除值value="Chinese",并将其打印出来。
System.out.println(map); //删除后的map集合
//map.clear(); //清空map集合
System.out.println(map.size()); //输出map集合的长度。
System.out.println(map.isEmpty()); //输出:false (非空的map集合)
System.out.println(map.containsKey("123")); //containsKey为Boolean值,是为true,否为false。
System.out.println(map.containsValue("Japan")); //map集合中的值包含Japan
System.out.println("========遍历方式1 先得到key 返回一个Set集合=====================");
//遍历方式1 先得到key 返回一个Set集合
Set<String> keySet = map.keySet();
for(String key:keySet){
//System.out.println(key);
System.out.println(key+"---"+map.get(key)); //map.get(key)通过key获取map的value值。
}
System.out.println("========遍历方式2 得到所有的key 和value 再从key value中分别获取key 和value==================");
//遍历方式2 得到所有的key 和value 再从key value中分别获取key 和value
Set<Entry<String,String>> entrySet = map.entrySet();
for(Entry<String,String> entry :entrySet){
System.out.println(entry.getKey()+"--"+entry.getValue());
}
System.out.println("========遍历方式3 迭代器 Map没有实现Iterator,不能【直接】使用迭代器,需要利用entrySet()===========");
//遍历方式3 迭代器 Map没有实现Iterator 不能直接使用迭代器
Set<Entry<String,String>> entrySet2 = map.entrySet();
Iterator<Entry<String,String>> it = entrySet2.iterator();
while(it.hasNext()){
Entry<String, String> entry = it.next();
//System.out.println(entry);
System.out.println(entry.getKey()+"--"+entry.getValue());
}
}
}
结果展示:

来源:https://www.cnblogs.com/superdrew/p/8084701.html