Removing unfilled values or null values from array of String in Java

前端 未结 7 1296
醉话见心
醉话见心 2020-12-16 02:22

I have following String Array tmp = [null, null, null, Mars, Saturn, Mars] coming after doing the operation - allSig[d3].split(\" \"); where

7条回答
  •  旧巷少年郎
    2020-12-16 02:41

    This is a very old question but this Java 8+ solution might be useful to someone:

    public static String[] removeElements(String[] allElements) { return Arrays.stream(allElements) .filter(Objects::nonNull) .collect(Collectors.toArray()); } or if you, like me, are a fan of readable code and don't want static methods to get in your way, you can simplify this even further using static imports:

    public static String[] removeElements(String[] allElements) { return stream(allElements).filter(Objects::nonNull).collect(toArray()); }

提交回复
热议问题