- 题目:已知:
- Map<Integer, String> map = new HashMap<Integer, String>();
- map.put(1, "90");
- map.put(2, "80");
- map.put(3, "70");
- map.put(4, "60");
- map.put(5, "50");
- map.put(6, "40");
- map.put(7, "30");
- map.put(8, "20");
- map.put(9, "10");
- 复制代码
- 求:
- ①将map集合的key值转变为key+(int)value,并输出转变后的map
- ②在第①步的基础上(map已经是新map了),删除map中50<key+(int)value<150的元素,并输出删除数据后的map
复制代码 答案如下:
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class MapTest {
- public static void main(String[] args) {
- Map<Integer, String> map = new HashMap<Integer, String>();
- map.put(61, "90");
- map.put(2, "80");
- map.put(3, "70");
- map.put(4, "60");
- map.put(5, "50");
- map.put(6, "40");
- map.put(7, "30");
- map.put(8, "20");
- map.put(9, "10");
- Set<Integer> keySet = map.keySet();
- Iterator<Integer> i = keySet.iterator();
- HashMap<Integer, String> map1 = new HashMap<Integer, String>();
- System.out.println("第一题结果:");
- while (i.hasNext()) {
- Integer key = i.next();
- String value = map.get(key);
- int add = new Integer(value);
- Integer newKey = key + add;
- map1.put(newKey, value);
- System.out.println(newKey + " " + value);
- }
- Set<Integer> keySet1 = map1.keySet();
- HashMap<Integer, String> map2 = new HashMap<Integer, String>();
- System.out.println("第二题结果:");
- for (Iterator<Integer> i1 = keySet1.iterator(); i1.hasNext();) {
- Integer key = i1.next();
- while (key.intValue() < 50 || key.intValue() > 150) {
- String value = map1.get(key);
- map2.put(key, value);
- System.out.println(key + " " + value);
- break;
- }
- }
- }
- }
复制代码
|
|