去除map中键为偶数的元素

来源:互联网 发布:什么是微信公众号矩阵 编辑:程序博客网 时间:2024/05/10 03:11
import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class TestMap {public static void main(String[] args) {HashMap<Integer,String> hm=new HashMap<Integer,String>();hm.put(1, "星期一");hm.put(2, "星期二");hm.put(3, "星期三");hm.put(4, "星期四");hm.put(5, "星期五");hm.put(6, "星期六");hm.put(7, "星期七");/*下面注释的方法会报错,报错原因以后详细分析*//*for(Map.Entry<Integer, String> entry:hm.entrySet()){Integer temp=entry.getKey();if(temp%2==0){hm.remove(1);}}*/Iterator<Map.Entry<Integer, String>> it = hm.entrySet().iterator();while(it.hasNext()){Map.Entry<Integer, String> entry = it.next();            Integer key = entry.getKey();            if(key%2==0){            it.remove();            }}for(Map.Entry<Integer, String> entry:hm.entrySet()){System.out.println(entry.getKey());}}}
运行结果

1

3

5

7