从列表中删除空/Null元素

huangapple go评论111阅读模式
英文:

Remove empty / null element from List

问题

你好我一直在尝试从列表中删除空/ null 元素尝试了多种方法不确定是否有遗漏的地方

public String getString() {
    List<String> result = new ArrayList<>();

    List<String> string1 = getDateResult();
    List<String> string2 = getStringResult();
    List<String> string3 = getNumberResult();
    List<String> string4 = getBookResult();

    result.add(string1);
    result.add(string2);
    result.add(string3);
    result.add(string4);

    // 以下是我已经尝试过的方法,但不起作用
    result.removeIf(List::isEmpty);
    result.removeAll(Arrays.asList(null, ""));

    return result;
}

示例输入

2020-08-10你好,,Book1 --> 无法删除空字符串
英文:

Hello i have been trying to remove empty / null element from List , have tried multiple things . not sure if i am missing something.

    public String getString() {
    List&lt;String&gt; result = new ArrayList&lt;&gt;();

    List&lt;String&gt; string1 = getDateResult();
    List&lt;String&gt; string2 = getStringResult();
    List&lt;String&gt; string3 = getNumberResult();
    List&lt;String&gt; string4 = getBookResult();

    result.add(string1);
    result.add(string2);
    result.add(string3);
    result.add(string4);

    // below are the things I already tried doesnt work 
    result.removeIf(List::isEmpty);
    result.removeAll(Arrays.asList(null,&quot;&quot;));

    return result;
    }

Example Input

2020-08-10 , Hello , , Book1 --> cant remove / delete the empty String.

答案1

得分: 2

如果您想要移除 List<List<String>> 中的空列表或空元素,

result.removeIf(list -> list == null || list.isEmpty());

或者如果您想要从内部列表中移除空元素,

result.forEach(list -> list.removeIf(ele -> ele == null || ele.isEmpty()));
英文:

If you want to remove null or empty List inside List List&lt;List&lt;String&gt;&gt;

result.removeIf(list-&gt;list==null || list.isEmpty());

or if you want to remove null or empty elements from inner lists

result.forEach(list-&gt;list.removeIf(ele-&gt;ele==null || ele.isEmpty()));

答案2

得分: 0

如果您想将一个列表添加到另一个列表中,可以使用addAll(..)方法。

这假设您不会在创建string1、string2列表的任何方法的结果中得到null

result.addAll(string1);
result.addAll(string2);

由于result是一个List<String>,您现在可以使用removeIf方法从您的result中移除任何无效的字符串。

如果您愿意使用Apache工具,您可以使用StringUtils.isBlank(str)函数。

英文:

If you want to add one list into another use the addAll(..) method.

This assumes that you don't get a null back as a result of any method that creates string1, string1 lists.

result.addAll(string1); result.addAll(string2); ...

As result is a List&lt;String&gt;, you can now use the removeIf method to remove any invalid strings from you result.

If you are open to using Apache utils you can use the StringUtils.isBlank(str)

huangapple
  • 本文由 发表于 2020年9月22日 10:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64002085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定