public class testMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
map.put("key1", "value3");
map.put("key1", "value4");
System.out.println("通过Map.keySet()遍历key和value");
System.out.println("1.1");
Set<String> keySet = map.keySet();
for (String s : keySet) {
System.out.println(s + "-->" + map.get(s));
}
System.out.println("1.2");
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + "-->" + map.get(key));
}
System.out.println("2.1");
System.out.println("通过Map.entrySet使用iterator遍历key和value");
Iterator<Map.Entry<String, String>> iterator1 = map.entrySet().iterator();
while (iterator1.hasNext()) {
Map.Entry<String, String> entry = iterator1.next();
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
System.out.println("3.1");
//容量大的时候推荐
System.out.println("通过Map.entrySet遍历key和value");
Set<Map.Entry<String, String>> setMap = map.entrySet();
for (Map.Entry<String, String> entry : setMap) {
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
System.out.println("4.1");
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String s : map.values()) {
System.out.println("value = "+s);
}
}
}
遍历Map的几种方法
最新推荐文章于 2024-11-01 14:48:20 发布