map转keySet通过键找值遍历
public class MapTest {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("李小龙", 23);
map.put("成龙", 26);
map.put("释小龙", 28);
map.put("陈小龙", 29);
Set<String> set = map.keySet();
//通过键找值遍历
for (String key : set) {
Integer value = map.get(key);
System.out.println(key + ":" + value);
}
}
}
map转entrySet
class Map2Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("李小龙", 23);
map.put("成龙", 26);
map.put("释小龙", 28);
map.put("陈小龙", 29);
//entrySet for循环
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
迭代器iterator遍历
class Map3Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("李小龙", 23);
map.put("成龙", 26);
map.put("释小龙", 28);
map.put("陈小龙", 29);
//使用迭代器(Iterator)遍历
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
forEach遍历
class Map4Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("李小龙", 23);
map.put("成龙", 26);
map.put("释小龙", 28);
map.put("陈小龙", 29);
//使用forEach
map.forEach((key,value)->{
System.out.println((key + ":" + value));
});
}
}