In Java, remove empty elements from a list of Strings

前端 未结 11 2419
余生分开走
余生分开走 2020-12-01 06:05

In Java, I have an ArrayList of Strings like:

[,Hi, ,How,are,you]

I want to remove the null and empty elements, how to change it so it is l

11条回答
  •  余生分开走
    2020-12-01 06:41

    Regarding the comment of Andrew Mairose - Although a fine solution, I would just like to add that this solution will not work on fixed size lists.

    You could attempt doing like so:

    Arrays.asList(new String[]{"a", "b", null, "c", "    "})
        .removeIf(item -> item == null || "".equals(item));
    

    But you'll encounter an UnsupportedOperationException at java.util.AbstractList.remove(since asList returns a non-resizable List).

    A different solution might be this:

    List collect =
        Stream.of(new String[]{"a", "b", "c", null, ""})
            .filter(item -> item != null && !"".equals(item))
            .collect(Collectors.toList());
    

    Which will produce a nice list of strings :-)

提交回复
热议问题