This is the format of my text file:
apricot
garlic
pineapple
attorney
banana
cantaloupe
Cherry
celery
cabbage
cucumber
fig
raspberry
Kiwi
lettuce
lime
mango
melon
grapefruit
Pear
pepper
Apple
radish
grape
The problem I'm having is that the text file contains extra blank lines and I'm not allowed to remove those lines. When I add the words to an arraylist it reads those extra blank lines and I'm wondering how I could remove those extra values.
This is what I've come up with so far:
arrWords = new ArrayList<Word>();
while (myReader.hasNextLine()) {
Word w = new Word(myReader.nextLine().toLowerCase().trim());
arrWords.add(w);
}
The arraylist is of type Word so I'm wondering how I could remove those blank values or somehow read the lines differently. I've tried multiple solutions like replace all or remove but none of them worked.
CodePudding user response:
try this:
while (myReader.hasNextLine()) {
String line = myReader.nextLine().toLowerCase().trim();
if (!line.isEmpty()) {
arrWords.add(new Word(line));
}
}
CodePudding user response:
Alternatively, you could use the stream API.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WordList {
public static void main(String[] args) throws IOException {
Path path = Paths.get("words.txt");
try (Stream<String> lines = Files.lines(path)) {
List<Word> arrWords = lines.filter(line -> !line.isBlank())
.map(line -> new Word(line.strip().toLowerCase()))
.collect(Collectors.toList());
arrWords.forEach(System.out::println);
}
}
}
class Word {
private String word;
public Word(String word) {
this.word = word;
}
public String toString() {
return word;
}
}
- Methods isBlank and strip were added in Java 11.
- Above code uses try-with-resources and NIO.2 as well as method references.