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
// Your work goes here
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
Stream
// call collect and pass the collecting by
Map
System.out.println("Result key value"+"pairs are");
//print each of the key value pairs
for(Map.Entry
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
Get step-by-step solutions from verified subject matter experts
