關於List裏的值爲null的情況處理

聯調階段會出現list的size爲1,但是list裏的值卻爲null.

一、例:

	// 初始化一個list,然後設置第0個元素的值爲null
	List<Integer> a = Collections.singletonList(null);
	if(CollectionUtils.isEmpty(a)){
		System.out.println(true);
	}else{
		System.out.println(false);
	}
	if(a == null || a.size() < 1){
		System.out.println(true);
	}else{
		System.out.println(false);
	}
	// 或者
	// 初始化一個list,添加一個爲null的值
	List<Integer> b = new ArrayList<>();
	b.add(null);
	if(CollectionUtils.isEmpty(b)){
		System.out.println(true);
	}else{
		System.out.println(false);
	}
	if(b == null || b.size() < 1){
		System.out.println(true);
	}else{
		System.out.println(false);
	}

	if(a.isEmpty()){
		System.out.println(true);
	}else{
		System.out.println(false);
	}

運行結果:
false
false
false
false
false

二、解決方案:

1.jdk8及以上:
	list.removeIf(Objects::isNull);
	
2.apache common包:
	CollectionUtils.filter(list, PredicateUtils.notNullPredicate());

3.谷歌 guva庫:
	Iterables.filter(list, Predicates.notNull())

4.循環判斷去除:
發佈了57 篇原創文章 · 獲贊 34 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章