Java 8 stream BufferedReader InputStream example

 230 total views,  3 views today

Welcome to Java 8 series. In this tutorial, you will learn about Java 8 stream BufferedReader InputStream example

This is a simple Java 8 stream program to identify the number of word occurrences in a file. This is a classic example of the word count map-reduce program. So let us try to solve in Java 8 stream.

We will be reading a file which contains a few lines of sentences. We will read as a Inputstream using FileReader and BufferedReader.

Let us create a File.

There are many places in this world to travel around.
Sikkim is one of the best places in India.
Once has to take atleast 10 days to visit Sikkim and enjoy its scenic beauty.

Word count example

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

public class StaticReference {
	public static void main(String[] args) throws IOException {
		File initialFile = new File("sample.txt");
		FileReader fr = new FileReader(initialFile);

		try (BufferedReader reader = new BufferedReader(fr)) {
		  reader
		  .lines()
		  .flatMap(i -> Arrays.stream(i.split(" ")))
		  .map(i -> i.toLowerCase())
		  .collect(Collectors.groupingBy(i -> i, Collectors.counting()))
		  .forEach((k, v) -> System.out.println(k + " - " + v));
		}

	}
}

Output

enjoy - 1
best - 1
scenic - 1
world - 1
are - 1
and - 1
around. - 1
of - 1
atleast - 1
has - 1
10 - 1
in - 2
one - 1
this - 1
its - 1
is - 1
many - 1
sikkim - 2
the - 1
take - 1
places - 2
once - 1
there - 1
days - 1
beauty. - 1
visit - 1
to - 3
travel - 1
india. - 1

Explanation

  1. We read a file using FileReader.
  2. We use BufferedReaders to read the content of the file.
  3. convert the file as a stream
  4. Apply flatMap() operation to convert the List<Collection of words> to List<each Word>. Basically we are trying to flatten the collection.
  5. Convert each word to lower case.
  6. Use collect() operation to group it based on the word and apply count operation.
  7. Print the result

Hope this post helps you to understand Java 8 stream BufferedReader InputStream example

Please leave a comment and gives us a thumbs up!.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.