集合1

/*
现在有一个map集合如下:
HashMap<Integer,String> map = new HashMap<Integer, String>();
map.put(1, "张三丰");
map.put(2, "周芷若");
map.put(3, "汪峰");
map.put(4, "灭绝师太");
要求:
1.遍历集合,并将序号与对应人名打印。
2.向该map集合中插入一个编码为5姓名为李晓红的信息
3.移除该map中的编号为1的信息
4.将map集合中编号为2的姓名信息修改为"周林"
*/
public class First {
public static void main(String[] args) {
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"张三丰");
map.put(2, "周芷若");
map.put(3, "汪峰");
map.put(4, "灭绝师太");
//获取所有的键,用keySet方法实现,得到一个key的set集合
Set<Integer> keySet = map.keySet();
//遍历键的集合,获取到每一个键,用增强for实现
for (Integer integer : keySet) {
//根据键去找值,用get(key)方法实现
String value = map.get(integer);
System.out.println(integer +" ,"+value);
}
System.out.println("------------------");
//向该map集合中插入一个编码为5姓名为李晓红的信息
map.put(5,"李晓红");
map.remove(1);
map.put(2,"周林");
for (Integer integer : keySet) {
//根据键去找值,用get(key)方法实现
String value = map.get(integer);
System.out.println(integer +" ,"+value);
}
}
}
上一篇:Map集合的两种取出方式:keySet()和entrySet()方法使用举例


下一篇:[转载] Java 遍历 Map 的 5 种方式