List 中去除 null 方法讨论
先看下面的程序段:
public static void main(String[] args) {
List<Integer> arrays = new ArrayList<Integer>();
arrays.add(2);
arrays.add(null);
arrays.add(456);
arrays.add(null);
arrays.add(789);
System.out.println(arrays);
}
注:一个list,向其中插入数据时,也插入一些null。程序输出如下:
[2, null, 456, null, 789]
现在有这个需求:去除list中null 元素。尝试的代码如下:
public static void main(String[] args) {
List<Integer> arrays = new ArrayList<Integer>();
arrays.add(2);
arrays.add(null);
arrays.add(456);
arrays.add(null);
arrays.add(789);
arrays.remove(null);
System.out.println(arrays);
}
调用remove(object)方法,程序的输出如下:
[2, 456, null, 789]
可以看出:只remove了第一个null元素。这不是我们期望的结果。继续找方法。考虑到有一个removeAll(Collection<?> c) ,尝试使用。代码如下:
public static void main(String[] args) {
List<Integer> arrays = new ArrayList<Integer>();
arrays.add(2);
arrays.add(null);
arrays.add(456);
arrays.add(null);
arrays.add(789);
List<Integer> nullArr = new ArrayList<Integer>();
nullArr.add(null);
arrays.removeAll(nullArr);
System.out.println(arrays);
}
程序的输出如下:
[2, 456, 789]
这是我们期望的结果。你可能会尝试下面这样使用:
arrays.removeAll(null);
很遗憾,程序出错了:Exception in thread "main" java.lang.NullPointerException。
到这里,我们似乎找到了解决问题的办法。但是,如果我们的系统中,有这种类型的List<E>,如List<TempProductDto>、List<merchantDto> 时,
我们要从这些List中移除掉null,就要创建如下的代码:
List<TempProductDto> nullTempProd = new ArrayList<TempProductDto>(1);
nullTempProd.add(null); List<MerchantDto> nullMerchant = new ArrayList<MerchantDto>(1);
nullMerchant.add(null);
每种类型,就要创建对应类型的List,并把null 放入到List中。是不是很麻烦。能不能写个公用的Util类呢?以下是我写的Util 类:
import java.io.Serializable;
import java.util.AbstractList;
import java.util.RandomAccess; public class NullCollection extends AbstractList<Object>
implements RandomAccess, Serializable { private static final long serialVersionUID = 5206887786441397812L; @Override
public Object get(int index) {
return null;
} @Override
public int size() {
return 1;
} public boolean contains(Object obj) {
return null == obj;
} private Object readResolve() {
return null;
}
}
import java.util.Collection;
import java.util.List; public class YHDCollectionUtils { public static final Collection NULL_COLLECTION = new NullCollection(); public static final <T> Collection<T> nullCollection() {
return (List<T>) NULL_COLLECTION;
}
}
使用我写的util类进行测试。代码如下:
public static void main(String[] args) {
List<Integer> arrays = new ArrayList<Integer>();
arrays.add(2);
arrays.add(null);
arrays.add(456);
arrays.add(null);
arrays.add(789);
arrays.removeAll(YHDCollectionUtils.nullCollection());
System.out.println(arrays);
}
执行结果如下:
[2, 456, 789]
Util 类可以成功的去除List中的null元素。
也许你会问:为什么要把null放入List中,只有2B青年会这么干?在一般业务中,我们确实不需要把null放入List中,但有一种场景:
从页面封装的List,如下面的代码:
<input name="dto.productList[0].name" value="我是名称1">
<input name="dto.productList[0].price" value="我是价格1"> <input name="dto.productList[2].name" value="我是名称2">
<input name="dto.productList[2].price" value="我是价格2"> <input name="dto.productList[4].name" value="我是名称3">
<input name="dto.productList[4].price" value="我是价格3">
OGNL 会自动把dto.productList[1]、dto.productList[3] 的object封装成null。因此,我们在操作dto.productList 前,优先把 productList 中null去除掉,防止 null 引起的空指针异常。
最后,欢迎各位拍砖。
List 中去除 null 方法讨论的更多相关文章
- vb中的null.nothing.empty区别
以下内容源自互联网: 变量 A.B.C.D 分别等于 0."".Null. Empty. Nothing 的哪一个? Dim A Dim B As String Dim C As ...
- PHP中去除字符串中的换行的方法
在PHP中,有时候我们需要对字符串的换行进行过滤,比如天涯PHP博客中文章页面的description信息,我是直接截取的文章内容,并过滤掉html符号,最终还要过滤掉其中的换行.下面整理一下常见的去 ...
- dedecms中去除首页index.html的方法
本文介绍了dedecms中去除首页index.html的方法,有需要的朋友参考下. dedecms织梦cms建站程序输入地址后,而打开的实际地址后面有个index.html. 这里分享下两种解决方 ...
- Python关于去除字符串中空格的方法
Python关于去除字符串中空格的方法 在编写程序时我们经常会遇到需要将字符串中的空格去掉的情况,通常我们可以使用下面几种解决方法: 1.strip()方法:该方法只能把字符串头和尾的空格去掉,但是不 ...
- python 中去除空格的方法
python 中去除空格的方法: def trim(s): l=[] for i in s: if i!=' ': l.append(i) return ''.join(l) 其中可以使用下面的 '' ...
- Python中去除字符串中的单个或多个空格的方法总结
python中去除字符串中空格的方法比较多,单个看起来也都比较简单 但是使用起来容易发生混淆 为了加深记忆 将常用的去除字符串中空格的方法汇总如下 方法一:strip()方法 >>> ...
- JavaScript中的面向对象的讨论(转)
前言 今天,WEB2.0时代的到来,给了JavaScript又一次大展身手的机会.Web2.0借助JavaScript技术,使得客户端的Web体验更加丰富多彩,同时JavaScript面对的问题域也变 ...
- 编写高质量代码:改善Java程序的151个建议(第一章:JAVA开发中通用的方法和准则)
编写高质量代码:改善Java程序的151个建议(第一章:JAVA开发中通用的方法和准则) 目录 建议1: 不要在常量和变量中出现易混淆的字母 建议2: 莫让常量蜕变成变量 建议3: 三元操作符的类型务 ...
- 如何在Java中避免equals方法的隐藏陷阱
摘要 本文描述重载equals方法的技术,这种技术即使是具现类的子类增加了字段也能保证equal语义的正确性. 在<Effective Java>的第8项中,Josh Bloch描述了当继 ...
随机推荐
- Parencodings - poj 1068
Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 22764 Accepted: 13344 Description L ...
- 【Python web自动化】之读取配置文件参数,利用cookie返回值进行跳过验证码进行登录操作
当进行Python的Web自动化时,会涉及到验证码问题,该如何跳过执行呢,下面请看代码: 1.首先新建配置文件*.ini格式 config.ini [db] #基础地址: baseurl = http ...
- 002android初级篇之ViewPager及PagerSlidingTabStrip listview的使用
002android初级篇之ViewPager及PagerSlidingTabStrip listview的使用 ViewPager ViewPager类直接继承了ViewGroup类,所有它是一个容 ...
- html5-框架网站
1.html5+:http://www.html5plus.org/ 2.hbuilder:http://www.dcloud.io/ 3.mui:http://dev.dcloud.net.cn/m ...
- Java图形界面实战案例——实现打字母游戏
实现打字母的游戏 这次这个案例能够说是头几次所讲的内容的一个技术汇总,主要是 运用了几大块的知识.我们先来定义一下案例的背景:在一个300*400的窗口上.有10个随机产生的字母下落,在键盘上敲击字母 ...
- wcf读取message内容
private string MessageToString(ref Message message) { WebContentFormat messageFormat = this.GetMessa ...
- word2vec_basic.py
ssh://sci@192.168.67.128:22/usr/bin/python3 -u /home/win_pymine_clean/feature_wifi/word2vec_basic.py ...
- thinkphp将APP_DEBUG常量设置为false后报错的问题
ThinkPHP 将 APP_DEBUG 常量设置为 false 后出现了下面的问题: Parse error: syntax error, unexpected T_STRING in \www\R ...
- 【python】-- Socket
socket socket本质上就是在2台网络互通的电脑之间,架设一个通道,两台电脑通过这个通道来实现数据的互相传递. 我们知道网络 通信 都 是基于 ip+port 方能定位到目标的具体机器上的具体 ...
- CF451E Devu and Flowers(容斥)
CF451E Devu and Flowers(容斥) 题目大意 \(n\)种花每种\(f_i\)个,求选出\(s\)朵花的方案.不一定每种花都要选到. \(n\le 20\) 解法 利用可重组合的公 ...