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<String> removeNull = subtract(nullList, Arrays.asList((String) null));
    Iterator<String> 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();) {
      list.remove(it.next());
    }
    return list;
  }

}

自定义方法,移除一个集合中所有的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<String> removeNull = removeNull(nullList);
    Iterator<String> it = removeNull.iterator();
    while (it.hasNext()) {
      String s = it.next();
      assertTrue(s != null);
    }
  }
  
  /**
   * 移除指定集合中的所有null值。
   *
   * @param source
   *          待移除null的集合,禁止传入null。
   * @return 新的结果集合。
   */
  public static <T> Collection<T> removeNull(final Collection<T> source) {
    assertArgumentNotNull(source, "source");

    ArrayList<T> list = new ArrayList<>(source.size());

    for (T value : source) {
      if (value != null) {
        list.add(value);
      }
    }
    return list;
  }

  /**
   * 断言参数不是null,若是null将抛出异常。
   * 
   * @param argument
   *          参数。
   * @param argumentName
   *          参数名。
   * @throws IllegalArgumentException
   *           当参数argument为null时抛出。
   * @since 1.17
   */
  public static void assertArgumentNotNull(Object argument, String argumentName)
      throws IllegalArgumentException {
    if (argument == null) {
      throw new IllegalArgumentException("指定集合不能为空");
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_36135928/article/details/86605104