Question: Java Question. Read all words from a file and group them by length. Print out how many words of each length are in the file.

Java Question. Read all words from a file and group them by length. Print out how many words of each length are in the file. Use collect and Collectors.groupingBy.

I did the coding but i have error in my word count. Please help.

import java.io.IOException;

import java.io.File;

import java.util.Scanner;

import java.util.Comparator;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.TreeMap;

import java.util.stream.Stream;

import java.util.stream.Collectors;

/**

* Read all words in a file and group them by length. Print out

* how many words of each length are in the file. Use collect

* and Collectors.groupingBy.

*/

public class words

{

public static void main(String[] args) throws IOException

{

String filename = "test.txt";

Map result = new TreeMap<>();

// Your work goes here

ArrayListwords = new ArrayList();

try (Scanner fileInput=new Scanner(new File("test.txt"));)

{

//read words from file

while(fileInput.hasNext())

{

//count words

int count = 0;

fileInput.next();

count++;

//add to words object

words.add(fileInput.next());

}

//display all words in file

System.out.println("All words are: ");

for(String current: words)

System.out.println(current);

// leave blank line

System.out.println();

//create stream

StreamwordStream = words.stream();

// call collect and pass the collecting by

Map> groups = words.stream().collect(Collectors.groupingBy(str -> str.length()));

System.out.println("Result key value"+"pairs are");

//print each of the key value pairs

for(Map.Entry>current:groups.entrySet())

System.out.println(current.getKey() +" "+current.getValue());

//count words

}

// Put your work above this line

System.out.println("Word counts in " + filename);

System.out.println(count);

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!