1.通过keySet()方法来遍历,此方法可以得到对应的key和value:
举一个Demo:
package map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTestSet {
//使用keySet进行遍历
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "hello1");
map.put(2, "hello2");
//遍历map的集合 1.通过Set方法获取key的集合
Set<Integer> key = map.keySet();
//利用Iterator
Iterator<Integer> it = key.iterator();
while(it.hasNext())
{ Integer keys = it.next();
System.out.println(keys);
System.out.println(map.get(keys));
}
}
}
其输出结果为:
1
hello1
2
hello2
2.通过EntrySet()方法来遍历,此方法可以获取到key-value键值对的集合:(推荐此方法)
Demo:
package map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapTestEntry {
//使用EntrySet()方法进行遍历
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "hello1");
map.put(2, "hello2");
Entry<Integer, String> entry;
Integer key;
String value;
// 获取键值对:key-value
Set<Entry<Integer, String>> entrySet = map.entrySet();
Iterator<Entry<Integer, String>> it = entrySet.iterator();
while (it.hasNext()) { // 这个entry包含了key-value的键值对
entry = it.next();
key = entry.getKey();
value = entry.getValue();
System.out.println("key = "+key+"\t"+"value = "+value);
}
}
}
输出结果为:
key = 1 value = hello1
key = 2 value = hello2
3.通过map.values()方法只能获取其中值的集合:
package map;
import java.util.HashMap;
import java.util.Map;
public class MapTestValues {
// 通过map.getValues取map的值的集合(list集合)
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "hello1");
map.put(2, "hello2");
// map.values()返回的是一个Collection集合 不能转成ArrayList(向下转型)
// 这里也不用用ArrayList的构造函数把Collection转成list
// 我们直接用foreach循环,因为Collection自己就带有Iterator迭代器
for (String str : map.values()) {
System.out.println(str);
}
}
}
其输出结果为:
hello1
hello2