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. Here is the test.txt file.

There now is your insular city of the Manhattoes belted round by wharves as Indian isles by coral reefs commerce surrounds it with her surf Right and left the streets take you waterward Its extreme downtown is the battery where that noble mole is washed by waves and cooled by breezes which a few hours previous were out of sight of land Look at the crowds of water gazers there

I did the coding but I have an error. Please help me to fix it. My word count did not appear in result.

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

int count = 0;

while(fileInput.hasNextLine())

{

//count words

fileInput.next();

String s = line.next();

String w[] =s.split(" ");

String l[] = s.split(" ");

count +=w.length;

// add words to 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(result);

}

}

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!