不错:
- package cn.exam;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- 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(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");
- System.out.println("原Map集合:");
- sopMap(map) ;
- System.out.println("①变换后的Map集合:");
- changeMap(map);
- sopMap(map);
- System.out.println("②清除数据后的Map集合:");
- removeMap(map);
- sopMap(map);
- }
-
- /**
- * @param map
- * 将map集合打印。
- */
- public static void sopMap(Map<Integer, String> map){
- System.out.println(map);
- }
-
- /**
- * @param map
- * 将map的key值变换为key+(int)value
- */
- public static void changeMap(Map<Integer,String>map){
- List<Integer> newKeyList = new ArrayList<Integer>();
- List<String> valueList = new ArrayList<String>();
- Set<Map.Entry<Integer, String>> st = map.entrySet();
- Iterator<Map.Entry<Integer, String>> it = st.iterator();
- while(it.hasNext()){
- Map.Entry<Integer, String> me=it.next();
- int key = me.getKey();
- String value =me.getValue();
- int newKey = key+Integer.parseInt(value);
- newKeyList.add(newKey);
- valueList.add(value);
- }
- map.clear();
- for(int i=0;i<newKeyList.size();i++){
- map.put(newKeyList.get(i), valueList.get(i));
- }
- }
-
- /**
- * @param map
- * 将map集合中满足条件的值移除。
- * 条件:map中50<key+(int)value<150;
- */
- public static void removeMap(Map<Integer,String>map){
- List<Integer> keyList = new ArrayList<Integer>();
- Set<Map.Entry<Integer, String>> st = map.entrySet();
- Iterator<Map.Entry<Integer, String>> it = st.iterator();
- int num =0;
- while(it.hasNext()){
- Map.Entry<Integer, String> me=it.next();
- int key = me.getKey();
- String value =me.getValue();
- num = key+Integer.parseInt(value);
- if(num>50&&num<150){
- keyList.add(key);
- }
- }
- for(int i=0;i<keyList.size();i++){
- map.remove(keyList.get(i));
- }
- }
- }
复制代码 |