Java 8 stream word count example

539 total views, 2 views today

Welcome to Java 8 series. In this tutorial, you will learn about java 8 stream word count example.

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

Let us create a List of Strings

List<String> list = new ArrayList<>();
list.add("There are many places in this world to travel around.");
list.add("Sikkim is one of the best places in India.");
list.add("Once has to take atleast 10 days to visit Sikkim and enjoy its scenic beauty.");

Word count example

public class StaticReference {
	public static void main(String[] args) {
	list
	  .stream()
	  .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 convert the list as a stream
  2. Apply flatMap() operation to convert the List<Collection of words> to List<each Word>. Basically we are trying to flatten the collection.
  3. Convert each word to lower case.
  4. Use collect() operation to group it based on the word and apply count operation.
  5. Print the result

Hope this post helps you to understand word count program using Java 8 stream.

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!.

12 thoughts on “Java 8 stream word count example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.