递归删除Map中的null值

工具类:

package com.tpf.map;




import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


public class MapTestUtil {

/**
* 递归删除map中的null值
* @param map
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map mapRemoveWithNullByRecursion(Map map){
Set> set = map.entrySet();
Iterator> it = set.iterator();
Map map2 = new HashMap();
while(it.hasNext()){
Entry en = it.next();
if(!(en.getValue() instanceof Map)){
if(null == en.getValue() || "".equals(en.getValue())){
it.remove();
}
}else{
map2 = (Map) en.getValue();
mapRemoveWithNullByRecursion(map2);
}
}
return map;
}
}

测试类:

package com.tpf.map;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


public class MapTest2 {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception{
Map map = new HashMap();
Map map2 = new HashMap();
Map map3 = new HashMap();
Map map4 = new HashMap();
String str = null ;
String str2 = "str2";
map.put("str", str);
map.put("str2", str2);
map.put("b", "map1");
map.put("a", null);
map.put("aa", null);

map.put("c", map2);
map2.put("11", "map2");
map2.put("12", null);

map2.put("d", map3);
map3.put("111", "map3");
map3.put("121", null);
map3.put("", null);
map3.put(null, null);

map4.put(1234, "map2value");
map4.put(12345, null);
map4.put(5432, "");
map3.put("map4", map4);
System.out.println(map);
System.out.println(MapTestUtil.mapRemoveWithNullByRecursion(map));

}
}

运行结果:


你可能感兴趣的:(javaSE)