Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Lukas Baumgartner
Lukas Baumgartner
14,817 Points

Java 8 Streams | Average word count

Hy!

I'm trying to do some exercise on Streams and encountered following problem:

I have a textfile, and i want to count the average number of words, for each line of the text file. Can someone tell me if my way of thinking is correct: Here's some pseudocode I think should do the trick once implemented:

double wordCount(String filepath){
  return Files.lines(Paths.get(filepath))
                          // make a wordarray of the line
                          // average the size of every wordarray with something like that
                              (collect(Collectors.averagingDouble())

Can someone please help me with that? How can I convert a line to a String array of words? How do I get the size of that array?

Thanks in advance!

1 Answer

Lukas Baumgartner
Lukas Baumgartner
14,817 Points

I solved it myself like this:

double wordcount(String filepath){
    return Files.lines(Paths.get(filepath))
                                  .map(line -> line.split("\\s")
                                  .map(array -> array.length)
                                  .collect(Collectors.averagingDouble(Double::new));
}