从java中的字符串数组中删除空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4150233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:05:59  来源:igfitidea点击:

Remove Null Value from String array in java

javaarraysstring

提问by Gnaniyar Zubair

How to remove null value from String array in java?

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

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

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

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

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

采纳答案by Vivin Paliath

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:

如果你想避免围栏错误并避免移动和删除数组中的项目,这里有一个有点冗长的解决方案,它使用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 nullto 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);    

    }
}

回答by Mud

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。您能看出这将如何应用吗?

回答by Kirk Woll

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

如果您确实想从数组中添加/删除项目,我可以建议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 reallyneed to put that back into an array:

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

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

回答by Emil

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
    }
});

回答by Ian S.

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);

回答by akhil_mittal

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

似乎没有人提到使用nonNull方法,该方法也可以streamsJava 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, ]

[苹果,,猫,狗,,空]

[苹果, , 猫, 狗, ]

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

如果我们也想合并 empty ,那么我们可以定义一个实用方法(在类中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.isNotEmptywhich can also be used.

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

回答by 18446744073709551615

A gc-friendly piece of code:

一段 gc 友好的代码:

public static<X> X[] arrayOfNotNull(X[] array) {
    for (int p=0, N=array.length; p<N; ++p) {
        if (array[p] == null) {
            int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
            X[] res = Arrays.copyOf(array, m);
            for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
            return res;
        }
    }
    return array;
}

It returns the original array if it contains no nulls. It does not modify the original array.

如果不包含空值,则返回原始数组。它不会修改原始数组。