从java中的String数组中删除Null值

时间:2021-02-05 00:13:15

How to remove null value from String array in java?

如何从java中的String数组中删除null值?

String[] firstArray = {"test1","","test2","test4",""};

I need the "firstArray" without null ( empty) values like this

我需要“firstArray”没有像这样的null(空)值

String[] firstArray = {"test1","test2","test4"};

6 个解决方案

#1


58  

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

如果你想避免使用fencepost错误并避免移动和删除数组中的项目,这里有一个使用List的有点冗长的解决方案:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

添加null以显示空String实例(“”)和null之间的差异。

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

由于这个答案大约是4.5岁,我正在添加一个Java 8示例:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

#2


16  

If you actually want to add/remove items from an array, may I suggest a List instead?

如果您确实想要从数组添加/删除项目,我可以建议使用List吗?

String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
    if (!s.equals(""))
        list.add(s);

Then, if you really need to put that back into an array:

然后,如果你真的需要把它放回一个数组:

firstArray = list.toArray(new String[list.size()]);

#3


4  

Using Google's guava library

使用谷歌的番石榴库

String[] firstArray = {"test1","","test2","test4","",null};

Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
    @Override
    public boolean apply(String arg0) {
        if(arg0==null) //avoid null strings 
            return false;
        if(arg0.length()==0) //avoid empty strings 
            return false;
        return true; // else true
    }
});

#4


2  

This is the code that I use to remove null values from an array which does not use array lists.

这是我用来从不使用数组列表的数组中删除空值的代码。

String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
    if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
        refinedArray[++count] = s; // Increments count and sets a value in the refined array
    }
}

// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);

#5


2  

It seems no one has mentioned about using nonNull method which also can be used with streams in Java 8 to remove null (but not empty) as:

似乎没有人提到过使用nonNull方法,它也可以与Java 8中的流一起用于删除null(但不是空),如下所示:

String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));

And the output is:

输出是:

[Apple, , Cat, Dog, , null]

[Apple ,, Cat,Dog ,, null]

[Apple, , Cat, Dog, ]

[苹果,猫,狗,]

If we want to incorporate empty also then we can define a utility method (in class Utils(say)):

如果我们想要合并为空,那么我们可以定义一个实用工具方法(在类Utils(比如说)中):

public static boolean isEmpty(String string) {
        return (string != null && !string.isEmpty());
    }

And then use it to filter the items as:

然后使用它来过滤项目:

Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);

I believe Apache common also provides a utility method StringUtils.isNotEmpty which can also be used.

我相信Apache common还提供了一个实用方法StringUtils.isNotEmpty,它也可以使用。

#6


-1  

Those are zero-length strings, not null. But if you want to remove them:

这些是零长度字符串,而不是null。但是如果你想删除它们:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

你可以将第二个移到第一个:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

如果你要为元素[1,2],然后[2,3]等做这个,你最终会将数组的全部内容移到左边,从而消除元素0.你能看出它会如何应用吗?

#1


58  

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

如果你想避免使用fencepost错误并避免移动和删除数组中的项目,这里有一个使用List的有点冗长的解决方案:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

添加null以显示空String实例(“”)和null之间的差异。

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

由于这个答案大约是4.5岁,我正在添加一个Java 8示例:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

#2


16  

If you actually want to add/remove items from an array, may I suggest a List instead?

如果您确实想要从数组添加/删除项目,我可以建议使用List吗?

String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
    if (!s.equals(""))
        list.add(s);

Then, if you really need to put that back into an array:

然后,如果你真的需要把它放回一个数组:

firstArray = list.toArray(new String[list.size()]);

#3


4  

Using Google's guava library

使用谷歌的番石榴库

String[] firstArray = {"test1","","test2","test4","",null};

Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
    @Override
    public boolean apply(String arg0) {
        if(arg0==null) //avoid null strings 
            return false;
        if(arg0.length()==0) //avoid empty strings 
            return false;
        return true; // else true
    }
});

#4


2  

This is the code that I use to remove null values from an array which does not use array lists.

这是我用来从不使用数组列表的数组中删除空值的代码。

String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
    if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
        refinedArray[++count] = s; // Increments count and sets a value in the refined array
    }
}

// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);

#5


2  

It seems no one has mentioned about using nonNull method which also can be used with streams in Java 8 to remove null (but not empty) as:

似乎没有人提到过使用nonNull方法,它也可以与Java 8中的流一起用于删除null(但不是空),如下所示:

String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));

And the output is:

输出是:

[Apple, , Cat, Dog, , null]

[Apple ,, Cat,Dog ,, null]

[Apple, , Cat, Dog, ]

[苹果,猫,狗,]

If we want to incorporate empty also then we can define a utility method (in class Utils(say)):

如果我们想要合并为空,那么我们可以定义一个实用工具方法(在类Utils(比如说)中):

public static boolean isEmpty(String string) {
        return (string != null && !string.isEmpty());
    }

And then use it to filter the items as:

然后使用它来过滤项目:

Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);

I believe Apache common also provides a utility method StringUtils.isNotEmpty which can also be used.

我相信Apache common还提供了一个实用方法StringUtils.isNotEmpty,它也可以使用。

#6


-1  

Those are zero-length strings, not null. But if you want to remove them:

这些是零长度字符串,而不是null。但是如果你想删除它们:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

你可以将第二个移到第一个:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

如果你要为元素[1,2],然后[2,3]等做这个,你最终会将数组的全部内容移到左边,从而消除元素0.你能看出它会如何应用吗?