How to get a Stream of space delimited Strings by reading a file?

Viewed 587

I am trying to read a text file and get a stream of the words inside it. By words, I mean simply Strings that are space delimited. I know Java has Files.lines() method that gives a Stream<String> but this is a stream of lines. I wish to post-process this stream by splitting each line with space. But the following code:

return Files.lines(Path.of(filename)).map((line)-> line.split(" "));

gives me a compilation error:

Type mismatch: cannot convert from Stream<Object> to Stream<String>Java(16777235)

Is there some casting that I need to do here to Stream<String> or is there a better way to get a stream of words?

2 Answers

String.split returns an array. You can use flatMap to wrap arrays into streams and connect them:

Stream<String> words = Files.lines(Path.of(filename))
    .map(line -> line.split(" "))
    .flatMap(Arrays::stream);
     

To add more alternative to the other two answers.

        Stream<String> stream = Arrays.stream(Files.readString(Paths.get(filename)).split(" "));

Is an alternative way but is essentially the same thing as the others.

List list = new ArrayList<>();

    try{
        Scanner s = new Scanner(new File(filename));
        while(s.hasNext()){
            String string = s.next();
            list.add(string);
        }
    }catch(Exception e){

    }

This is a way that should be more efficient as the Scanner naturally reads until it hits a space.

Related