Java Stream How to - Count unique word in a file with Lambda








Question

We would like to know how to count unique word in a file with Lambda.

Answer

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
//from  www. jav a2  s.com
public class Main {

  public static void main(String[] args) throws Exception{

    long uniqueWords = Files.lines(Paths.get("Main.java"), Charset.defaultCharset())
                            .flatMap(line -> Arrays.stream(line.split(" ")))
                            .distinct()
                            .count();

    System.out.println("There are " + uniqueWords + " unique words in data.txt");

  }

}

The code above generates the following result.