- package schooltest;
- import java.util.*;
- /*
- * 求:
- ①将map集合的key值转变为key+(int)value,并输出转变后的map
- ②在第①步的基础上(map已经是新map了),删除map中50<key+(int)value<150的元素,并输出删除数据后的map
- */
- public class Test40 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Map<Integer,String> m = answer1();
- System.out.println(m);
- Map<Integer,String> m2 =answer2(m);
- System.out.println(m2);
-
- }
- public static Map<Integer,String> answer1()
- {
- Map<Integer,String> hm = new HashMap<Integer,String>();
- Map<Integer,String> hm2 = new HashMap<Integer,String>();//不能同时操作hm(既增加 有删除),所以笨办法,又定义了一个
-
- hm.put(1, "90");
- hm.put(2, "80");
- hm.put(3, "70");
- hm.put(4, "60");
- hm.put(5, "50");
- hm.put(6, "40");
- hm.put(7, "30");
- hm.put(8, "20");
- hm.put(9, "10");
- Set<Integer> keySet = hm.keySet();
- for(Integer key:keySet)
- {
- String value= hm.get(key);
- Integer key2 = key+Integer.parseInt(value);
- hm2.put(key2, value);
- }
- //System.out.println(hm2);
- hm.clear();
- //System.out.println(hm);
- Set<Integer> keySet2 = hm2.keySet();
- for(Integer key2:keySet2)
- {
- String value2= hm2.get(key2);
- hm.put(key2, value2);
- }
- return hm;
- }
- public static Map<Integer,String> answer2(Map<Integer,String> m)
- {
- Set<Map.Entry<Integer, String>> entrySet = m.entrySet();
- Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
- while(it.hasNext())
- {
- Map.Entry<Integer, String> me =it.next();
- Integer key =me.getKey();
- if(key>50&&key<150)
- it.remove();
- }
- return m;
- }
- }
复制代码
写的有些复杂,在iterator中对集合进行删除、添加操作会是代码更加简洁、健全。同时第二问也把题意理解错了,第二题不是50<key<150,而是新map的50<key+value<150.
继续努力,加油。 |