Java Programming: Complete the following program: import java.util.Scanner; impo
ID: 3686171 • Letter: J
Question
Java Programming:
Complete the following program:
import java.util.Scanner;
import java.util.stream.Collectors;
/** * Write a program that reads all words from a file and, using a Stream,
* prints all distinct words with at most four letters.
from Horstmann, Big Java 6th Ed.
*/
public class PrintDistinctShortWords {
public static void main(String[] args) throws IOException {
String filename = "test.txt";
// Uses try-with to open the file
try (Scanner in = new Scanner(new File(filename))) {
// Read all the words in the file
List wordList = new ArrayList<>();
while (in.hasNext()) {
wordList.add(in.next());
}
// Turn the wordList into a stream of words
// modify the following line to print all the distinct words in the stream that have at most four letters (in some order). You may modify other statements.
wordList.stream();
}
}
}
Explanation / Answer
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.*;
/**
* * Write a program that reads all words from a file and, using a Stream,
*
* prints all distinct words with at most four letters.
*
* from Horstmann, Big Java 6th Ed.
*/
public class PrintDistinctShortWords {
public static void main(String[] args) throws IOException {
String filename = "test.txt";
// Uses try-with to open the file
try (Scanner in = new Scanner(new File(filename))) {
// Read all the words in the file
//declaring a Map to store all words and its count
HashMap<String,Integer> wordList = new HashMap<>();
// adding all words into map
while (in.hasNext()) {
String word = in.next();
if(wordList.containsKey(word)){
wordList.put(word, wordList.get(word) + 1); // incrementing count
}else{
wordList.put(word, 1);
}
}
// now iterating through map and checking non-repeating words
for(Map.Entry<String, Integer> entry : wordList.entrySet()){
// if count is 1 and size is <=4, then print
if( entry.getValue() == 1 && entry.getKey().length() <= 4)
System.out.println(entry.getKey());
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.