package com.lzl.main;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
String[] strArray = { "zhangsan", "lisi", "wangwu", "zhaoliu","linglingqi" };
for (int i = 0; i < strArray.length; i++) {
map.put("name" + i, strArray[i]);
}
System.out.println("-------------keySetUseFor-------------");
mapTestByKeySetUseFor(map);
System.out.println("-------------keySetUseIterator--------");
mapTestByKeySetUseIterator(map);
System.out.println("-------------EntrySetUseFor-----------");
mapTestByEntrySetUseFor(map);
System.out.println("-------------EntrySetUseIterator------");
mapTestByEntrySetUseIterator(map);
System.out.println("-------------ValuesUseFor-------------");
mapTestByValuesUseFor(map);
System.out.println("-------------ValuesUseIterator--------");
mapTestByValuesUseIterator(map);
}
// 1.利用keySet()方法进行For遍历
private static void mapTestByKeySetUseFor(Map<String, String> map) {
if (map != null && !map.isEmpty()) {
Set<String> keySet = map.keySet();
for (String key : keySet) {
String value = map.get(key);
System.out.println("key:" + key + ",value:" + value);
}
}
}
// 2.利用keySet()方法进行Iterator遍历
private static void mapTestByKeySetUseIterator(Map<String, String> map) {
if (map != null && !map.isEmpty()) {
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
String value = map.get(key);
System.out.println("key:" + key + ",value:" + value);
}
}
}
// 3.利用entrySet()方法进行For遍历
private static void mapTestByEntrySetUseFor(Map<String, String> map) {
if (map != null && !map.isEmpty()) {
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
}
}
// 4.利用entrySet()方法进行Iterator遍历
private static void mapTestByEntrySetUseIterator(Map<String, String> map) {
if (map != null && !map.isEmpty()) {
Iterator<Entry<String, String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
}
}
// 5.利用values()方法进行For遍历,但不能遍历key。
private static void mapTestByValuesUseFor(Map<String, String> map) {
if (map != null && !map.isEmpty()) {
Collection<String> collection = map.values();
for (String value : collection) {
System.out.println("value:" + value);
}
}
}
// 6.利用values()方法进行Iterator遍历,但不能遍历key。
private static void mapTestByValuesUseIterator(Map<String, String> map) {
if (map != null && !map.isEmpty()) {
Iterator<String> iter = map.values().iterator();
while (iter.hasNext()) {
String value = iter.next();
System.out.println("value:" + value);
}
}
}
}
Java中Map集合的遍历
最新推荐文章于 2024-07-01 16:13:53 发布