Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing empty element from Array(Java)

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;
}
like image 432
Ruben Avatar asked Dec 19 '22 10:12

Ruben


2 Answers

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);
like image 162
Jérôme Avatar answered Dec 26 '22 21:12

Jérôme


Array are immutable so the size stays the same you need to create a new Array So if you create a new Array base on the Size of the Old array you will still have null elements

If you want to use arrays only you need to count the non null elements in the array to get the size of the new Array. It just easier to use a List/ArrayList

public String[] wordsWithout(String[] words, String target) {
    List<String> tempList=new ArrayList<String>();
    for(int i = 0; i < words.length; i = i +1){

        if (words[i]!=null||words[i].trim().length()>0){
            tempList.add(words[i]);
        }

    }
    return (String[]) tempList.toArray();
}
like image 36
Joe ONeil Avatar answered Dec 26 '22 21:12

Joe ONeil