从数组中删除空元素(Java) [英] Removing empty element from Array(Java)

查看:34
本文介绍了从数组中删除空元素(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);

这篇关于从数组中删除空元素(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆