刪除List所有元素都爲空的行數據

在查詢過程中,可能會遇到查詢出行數據都爲null的情況,如下圖所示:

我們可以採用以下的方法刪除全爲空的行數據

1. 使用原生Java刪除空行

    @Test
    public void testRemoveNullElement() {
        List<Integer> list =  new ArrayList<>(Arrays.asList(null, 1, null));
        
        while (list.remove(null));

        assertThat(list, hasSize(1));
    }

 debug結果:

2. 使用Apache Commons Collections刪除空行

    @Test
    public void testRemoveNullElementByApache() {
        List<Integer> list =  new ArrayList<>(Arrays.asList(null, 1, 2, null, 3, null));

        CollectionUtils.filter(list, PredicateUtils.notNullPredicate());

        assertThat(list, hasSize(3));
    }

 其中,filter的具體實現方法爲:

public static <T> boolean filter(final Iterable<T> collection, final Predicate<? super T> predicate) {
        boolean result = false;
        if (collection != null && predicate != null) {
            for (final Iterator<T> it = collection.iterator(); it.hasNext();) {
                if (!predicate.evaluate(it.next())) {
                    it.remove();
                    result = true;
                }
            }
        }
        return result;
    }

3. 使用java8的lambdas表達式刪除空行

@Test
public void testRemoveNullElementByLambdas() {
     List<Integer> list =  new ArrayList<>(Arrays.asList(null, 1, 2, null, 3, null));

     list.removeIf(Objects::isNull);

     assertThat(list, hasSize(3));
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章