Stream
operations do not mutate your underlying List
. You need to collect the result after map
.
Since a Stream can only be processed once, you might as well do the entire transformation chain at once (without intermediate variables). I'm guessing that you want a single array (or list) containing all the "words" (so I used flatMap to merge to a single List<String>
):
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
Pattern pattern = Pattern.compile(" +");
List<String> allWords = bufferedReader.lines()
.map(String::toLowerCase)
.map(line -> line.replaceAll("[^a-z0-9]", " "))
.flatMap(pattern::splitAsStream)
.collect(Collectors.toList());
If you want "word" count, replace collect(...)
with count()
.
You can also merge replaceAll()
and split()
into 1 action, skipping toLowerCase()
:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
Pattern pattern = Pattern.compile("[^A-Za-z0-9]+");
List<String> allWords = bufferedReader.lines()
.flatMap(pattern::splitAsStream)
.map(String::toLowerCase) // if still needed
.collect(Collectors.toList());
Edits:
190805: Simplified flatMap as suggested by @greg-449
190806: Merged replace & split as suggested by @Holger