数组含空值求助:读取文本文件单词排序时空值无法移除
Hey there! Let's dig into why your null filtering isn't working and get this sorted out (pun intended 😊).
First off, the most likely issue is that you're creating a filtered array but not assigning it back to your original w.words variable. Let's break this down:
Why Your Current Code Fails
When you run:
Arrays.stream(w.words).filter(x->x != null).toArray();
This creates a brand new array with the nulls removed—but if you don't save this new array back to w.words, your original array (with nulls) stays unchanged. That's why you still see nulls when sorting!
Plus, the default toArray() method returns an Object[] instead of a String[] (assuming w.words is a String array), which can cause type issues if you try to assign it directly.
The Fix: Assign the Filtered Array & Use Correct Type
Update your code to assign the filtered array back to w.words, and specify the target array type to avoid casting problems:
// Filter out nulls AND blank/empty strings (optional but recommended) w.words = Arrays.stream(w.words) .filter(word -> word != null && !word.trim().isEmpty()) .toArray(String[]::new);
Let's Break This Down:
filter(word -> word != null && !word.trim().isEmpty()): Removes both null values and any empty/whitespace-only strings that might have slipped in during file reading.toArray(String[]::new): Tells the stream to return aString[]instead of anObject[], matching your original array's type.- Assigning back to
w.words: Replaces your original array with the cleaned-up version.
Extra Step: Verify the Filtered Array
To make sure the filtering worked, you can print the array before sorting:
System.out.println("Cleaned array: " + Arrays.toString(w.words));
Full Workflow Example
Here's how it fits into your overall process:
// After reading words from the file into w.words // Clean the array w.words = Arrays.stream(w.words) .filter(word -> word != null && !word.trim().isEmpty()) .toArray(String[]::new); // Now sort in descending order Arrays.sort(w.words, Collections.reverseOrder());
That should eliminate the nulls and let your sorting work as expected!
内容的提问来源于stack exchange,提问作者abhishek ranjan

