[code]
public Map NullConvertEmptyForMap(Map map) {
Map convertedMap = null;
Set mapset = map.entrySet();
String EMPTYSTR = "";
if (map != null) {
convertedMap = new HashMap();
for (Iterator it = mapset.iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
if (entry.getValue() == null) {
convertedMap.put(entry.getKey(), EMPTYSTR);
}
else {
convertedMap.put(entry.getKey(), entry.getValue());
}
}
}
return convertedMap;
}[/code]
[code]
public List NullConvertEmptyForList(List list) {
List convertedList = null;
if (list != null && list.size() > 0) {
convertedList = new ArrayList();
Iterator it = list.iterator();
while (it.hasNext()) {
Map map = (Map) it.next();
Map convertedMap = NullConvertEmptyForMap(map);
convertedList.add(convertedMap);
}
}
return convertedList;
}
[/code]
public Map NullConvertEmptyForMap(Map map) {
Map convertedMap = null;
Set mapset = map.entrySet();
String EMPTYSTR = "";
if (map != null) {
convertedMap = new HashMap();
for (Iterator it = mapset.iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
if (entry.getValue() == null) {
convertedMap.put(entry.getKey(), EMPTYSTR);
}
else {
convertedMap.put(entry.getKey(), entry.getValue());
}
}
}
return convertedMap;
}[/code]
[code]
public List NullConvertEmptyForList(List list) {
List convertedList = null;
if (list != null && list.size() > 0) {
convertedList = new ArrayList();
Iterator it = list.iterator();
while (it.hasNext()) {
Map map = (Map) it.next();
Map convertedMap = NullConvertEmptyForMap(map);
convertedList.add(convertedMap);
}
}
return convertedList;
}
[/code]
本文介绍了一种在Java中处理集合的方法,特别是如何将Map和List中的null值转换为空字符串,以避免程序因空指针异常而崩溃。代码示例展示了如何遍历Map和List,并为null值提供默认值。
5590

被折叠的 条评论
为什么被折叠?



