从数组中删除空元素(Java)

问题描述:

我试图通过将现有元素复制到新数组来从数组中删除空元素.但是,即使我在 for 循环中初始化它,新数组的初始化也会导致我的返回值为 null.

I'm trying to remove the empty element from the array by copying the existing element to a new array. However, initialization of the new array is causing my return value to be null even when I initialize it within the for loop.

public String[] wordsWithout(String[] words, String target) {
    for(int i = 0; i < words.length; i = i +1){
        String store[] = new String[words.length];
        if (words[i] == target){
            words[i] ="";
        }
        else if(words[i] != target){
            words[i] = store[i];
        }       
    }
    return words;
}

我实际上不确定您想要实现什么,但是如果您想从数组中删除一个空字符串,您可以使用流和过滤器来实现像这样的Java 8:

I'm actually not sure what you want to achieve but if you want to remove an empty String out of your array you can do it with streams and filters in java 8 like this:

String[] objects = Arrays.stream(new String[]{"This","", "will", "", "", "work"}).filter(x -> !x.isEmpty()).toArray(String[]::new);