Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove "null" elements in an array?

I am currently doing a coding challenge that states:

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below (which is an image of a QWERTY keyboard).

Example:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

What I have done to solve this is to write a for loop, then do if statements that replace all rows (like QWERTY) to "" and if the length of this is greater than 1, then you can not type that word in one row. I am getting almost the correct output, but my array contains null elements.

My output is:

[null,"Alaska","Dad",null]

How can I return an array that does not have these null elements? To complete this challenge, I have to return a String[] array. I can not use an ArrayList to return.

class Solution {
    public String[] findWords(String[] words) {
    String[] result = new String[words.length];

    String row1 = "qwertyuiop";
    String row2 = "asdfghjkl";
    String row3 = "zxcvbnm";

    for (int i = 0 ; i < words.length; i++) {
        if (words[i].toLowerCase().replaceAll("[" + row1 + "]", "").length() == 0 ||
           words[i].toLowerCase().replaceAll("[" + row2 + "]", "").length() == 0 ||
           words[i].toLowerCase().replaceAll("[" + row3 + "]", "").length() == 0) {
            if (words[i] != null) {
                result[i] = words[i];
            }


        }
       }

    return result;
    }


}
like image 495
SaturnsBelt Avatar asked Dec 14 '22 13:12

SaturnsBelt


1 Answers

Using this one liner:

Arrays.stream(result).filter(Objects::nonNull).toArray(String[]::new)

Filters the array and get all objects that are nonNull. Do not forget to transform the stream back to an array.

like image 64
P. van der Laan Avatar answered Dec 23 '22 23:12

P. van der Laan