Java教程

Java集合中移除所有的null值

本文主要是介绍Java集合中移除所有的null值,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java集合中移除所有的null值
https://blog.csdn.net/qq_36135928/article/details/86605104

org.apache.commons.collections.subtract方法只能移除第一个null元素。

public class CollectionRemoveNullTest {
@Test

public void test() {

List<String> nullList = new ArrayList<>();

nullList.add("a");

nullList.add(null);

nullList.add("b");

nullList.add("c");

nullList.add(null);
Collection&lt;String&gt; removeNull = subtract(nullList, Arrays.asList((String) null));
Iterator&lt;String&gt; it = removeNull.iterator();
while (it.hasNext()) {
  String s = it.next();
  assertTrue(s != null);
}

}
/**

Returns a new {@link Collection} containing <tt><i>a</i> - <i>b</i></tt>.
The cardinality of each element <i>e</i> in the returned {@link Collection}
will be the cardinality of <i>e</i> in <i>a</i> minus the cardinality of
<i>e</i> in <i>b</i>, or zero, whichever is greater.

@param a

     the collection to subtract from, must not be null


@param b

     the collection to subtract, must not be null


@return a new collection with the results
@see Collection#removeAll

*/

public static Collection subtract(final Collection a, final Collection b) {

ArrayList list = new ArrayList(a);

for (Iterator it = b.iterator(); it.hasNext()

	
这篇关于Java集合中移除所有的null值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!