Java——》Map遍历
推荐链接:
总结——》【Java】
总结——》【Mysql】
总结——》【Spring】
总结——》【SpringBoot】
总结——》【MyBatis、MyBatis-Plus】
Java——》Map遍历
方法 | 描述 | 备注 |
---|---|---|
keySet() | K 值集合 = Set 集合 | 需要遍历2次,才能获取 K 和 V 第1次遍历:获取K 第2次遍历:通过get(K)获取V |
values() | V 值集合 = List集合 | 只能获取V |
entrySet() | K-V 值组合 = Map.Entry对象 | 只遍历1次,就能获取K 和 V |
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(16);
map.put("k1", "v1");
map.put("k2", "v2");
// 第一种:分别遍历key和value
System.out.println("------第一种:分别遍历key和value------");
// 使用keySet(),遍历key
for (String key : map.keySet()) {
System.out.println("key:" + key);
}
// 使用values(),遍历value
for (String value : map.values()) {
System.out.println("value:" + value);
}
// 第二种:使用keySet(),遍历key和value
System.out.println("------第二种:使用keySet(),遍历key和value------");
for (String key : map.keySet()) {
System.out.println("key= " + key + " and value= " + map.get(key));
}
// 第三种:使用迭代器iterator(),遍历key和value
System.out.println("------第三种:使用iterator()迭代器,遍历key和value------");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
// 第四种:使用entrySet(),遍历key和value(推荐,尤其是容量大时)
System.out.println("------第四种:使用entrySet(),遍历key和value------");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
}
}
还没有评论,来说两句吧...