How can I remove “null” elements in an array?

  • A+
Category:Languages

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

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: