大家好,又见面了,我是全栈君。
1:根据JDK的新特性,用For循环Map,例如循环Map的Key
Map<Object , Object> map = new HashMap<Object, Object>();
for (int i = 0; i < 10; i++) {
map.put(i, i+1);
}
for (Object key : map.keySet()) {
System.out.println("key = " + key);
}
2:对整Map的key和value都进行循环,如下:
for(Map.Entry<String, Object> entry : paraMap.entrySet())
{
System.out.println(entry.getKey()+": "+entry.getValue());
}
3:使用Iterator
Iterator it = paraMap.entrySet().iterator();
while (it.hasNext())
{
Map.Entry map = (Map.Entry)it.next();
System.out.println(map .getKey() + " = " + map .getValue());
}
对上面的内容进行更新!将三种方式完整呈现!
package com.dufyun.javase.jihe;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* 练习循环map集合中key和value的方法
* @author aflyun
*
*
*/
public class TestMap {
public static void main(String[] args) {
Map<Object , Object> map = new HashMap<Object, Object>();
for (int i = 0; i < 10; i++) {
map.put(i, i+1);
}
firstLoopMap(map);
secodnLoopMap(map);
thirdLoopMap(map);
}
/**
* 1:循环 map 中的key<br/>
* 根据JDK的新特性,用For循环Map,例如循环Map的Key 和 value
* @param map
*/
public static void firstLoopMap(Map<Object, Object> map) {
for (Object key : map.keySet()) {
System.out.println("key = " + key +"--value = " + map.get(key));
}
}
/**
* 2:循环 map 中的key 和 value<br/>
* entrySet
* @param map
*/
public static void secodnLoopMap(Map<Object , Object> map) {
for (Map.Entry<Object, Object> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() +"--value = " + entry.getValue());
}
}
/**
* 3:循环Map的key 和value<br/>
* iterator
* @param map
*/
public static void thirdLoopMap(Map<Object, Object> map) {
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Object, Object> m = (Entry<Object, Object>) it.next();
System.out.println("key = " + m.getKey() +"---value = "+ m.getValue());
}
}
}
输出的内容:
key = 0---value = 1
key = 1---value = 2
key = 2---value = 3
key = 3---value = 4
key = 4---value = 5
key = 5---value = 6
key = 6---value = 7
key = 7---value = 8
key = 8---value = 9
key = 9---value = 10
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/121280.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...