Question

This last lab teaches you to think and solve problems in the functional programming framework of...

This last lab teaches you to think and solve problems in the functional programming framework of the Java 8 computation streams. Therefore in this lab, you are absolutely forbidden to use any conditional statements (either if or switch), loops (either for, while or do-while) or even recursion. All computation must be implemented using only computation streams and their operations!

In this lab, we also check out the Java NIO framework for better file operations than those offered in the old package java.io and the class File. Your methods receive a Path as an argument, referring to the text file in your file system whose contents your methods will then process with computation streams. Write both of the following methods inside a new class named StreamExercises.

public int countLines(Path path, int thres) throws IOException

This method should first use the utility method Files.lines to convert the given path into an instance of Stream<String> that produces the lines of this text file as a stream of strings, one line at the time. The method should then use filter to keep only those whose length is greater or equal to the threshold value thres, and in the end, return a count how many such lines the file contains.

public List<String> collectWords(Path path) throws IOException


This method should also use the same utility method Files.lines to first turn its parameter path into a Stream<String>. Each line should be converted to lowercase and broken down to individual words that are passed down the stream as separate String objects (the stream operation flatMap will be handy here). Split each line into its individual words using the separator regex "[^a-z]+" for the method split in String. In the next stages of the computation stream, discard all empty words, and sort the remaining words in alphabetical order. Multiple consecutive occurrences of the same word should then be removed (use the stream operation distinct, or if you want to do this yourself the hard way as an exercise, write a custom Predicate<String> subclass whose method test accepts its argument only if it was the first one or distinct from the previous argument), and to wrap up this computation stream, collected into a List<String> that is returned as the answer.

*TEST FILE*

import java.util.*;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.*;
import java.io.*;

public class StreamExercisesTest {
    
    private static int TRIALS = 10000;
    private static int SEED = 9999;
    
    @Test
    public void testCountLines() {
        StreamExercises se = new StreamExercises();
        try {
            assertEquals(se.countLines(Paths.get("warandpeace.txt"), 70), 21079);
        }
        catch(IOException e) {
            System.out.println("Unable to read warandpeace.txt!");
            assertTrue(false);
        }
    }
    
    @Test
    public void testCollectWords() {
        StreamExercises se = new StreamExercises();
        try {
            List<String> words = se.collectWords(Paths.get("warandpeace.txt"));
            assertEquals(17465, words.size());
            assertEquals("accomplished", words.get(100));
            assertEquals("sundays", words.get(15000));
        }
        catch(IOException e) {
            System.out.println("Unable to read warandpeace.txt!");
            assertTrue(false);
        }
        
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamExercises {
    public int countLines(Path path, int thres) throws IOException{
        Stream<String> lines = Files.lines(path); // to get lines from file
        Stream<String> l =  lines.filter(line -> line.length() >= thres); // filter lines which are less than threshold length
        return (int) l.count(); // return the number of lines
    }

    public List<String> collectWords(Path path) throws IOException{
        Stream<String> lines = Files.lines(path); // extract lines from file
        Stream<String> l = lines.map(line -> line.toLowerCase()); // convert lines to lower case
        Stream<String> words = l.map(line-> line.split("[^a-z]+")).flatMap(Arrays::stream); // split the lines to extract word using regex and then flattening the Stream<String[]> to Strema<String>
        Stream<String> noempty_word = words.filter(word -> word.length() > 0).sorted(); // removing empty words and then sorting the stream of words
        List<String> ans = noempty_word.distinct().collect(Collectors.toList()); // extracting distinct words and converting them to list
        return ans; returning resulting list
    }
}

Explanation:

CountLines Funtion:

Stream<String> lines = Files.lines(path) : This line extract lines from file and assign it to Stream of string.

Stream<String> l =  lines.filter(line -> line.length() >= thres) : This line uses a stream function to filter out those lines whose length is greater than thresholde value.
return (int) l.count() : This line returns the count of lines as an int.

collectWords Function:

Stream<String> lines = Files.lines(path):  This line extract lines from file and assign it to Stream of string. 
Stream<String> l = lines.map(line -> line.toLowerCase()) : convert each line in Stream to lower case.
Stream<String> words = l.map(line-> line.split("[^a-z]+")).flatMap(Arrays::stream) : split lines to etract word using regex and then flattening Stream of Stream of String to Stream of String.
Stream<String> noempty_word = words.filter(u -> u.length() > 0).sorted() : remove empty words from word Stream and sorts the word in alphabetical order.
List<String> ans = noempty_word.distinct().collect(Collectors.toList()) : filter out distinct words and covert them into list of string .
return ans :  return the list
Add a comment
Know the answer?
Add Answer to:
This last lab teaches you to think and solve problems in the functional programming framework of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Lab Description Sort all words by comparing the length of each word. The word with the...

    Lab Description Sort all words by comparing the length of each word. The word with the smallest length would come first. If you have more than one word with the same length, that group would be sorted alphabetically Input: The data file contains a list of words. The first line in the data file is an integer that represents the number of data sets to follow Output: Output the complete list of words in order by length. Sample Data 10...

  • In Java, you'll find that it contains several methods that have not yet been finished. For now, the methods contain...

    In Java, you'll find that it contains several methods that have not yet been finished. For now, the methods contain only a placeholder return value so that the code will compile. Fill in your own implementation. public class SomePracticeStringMethods { /* * returns true if c is a letter in the word "temple" or false otherwise */ public static boolean inTU(char c) { /* placeholder just so that the function * compiles. fill in your implementation here. * * there...

  • Part 2: Programming with Exceptions In this part of the lab , you will write a...

    Part 2: Programming with Exceptions In this part of the lab , you will write a program that fetches the information stored at a give URL on the web and saves that data to a file. This will also include networking and file operations and partly an exercise in using exceptions. For doing I/O, Java has a pair of nice abstractions: InputStream and OutputStream. These are abstract classes in the package java.io. An InputStream is a place from which you...

  • Need help with a number guessing game in java 1) You should store prior guessses in...

    Need help with a number guessing game in java 1) You should store prior guessses in a linked list, and the nodes in the list must follow the order of prior guesses. For example, if the prior guesses are 1000, 2111, 3222 in that order, the nodes must follow the same order 2) You should store the candidate numbers also in a linked list, and the nodes must follow the order of numbers (i.e. from the smallest to the largest)....

  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

  • Using the diagram below and the starter code, write Document Processor that will read a file...

    Using the diagram below and the starter code, write Document Processor that will read a file and let the user determine how many words of a certain length there are and get a count of all of the word lengths in the file. Your program should do the following: The constructor should accept the filename to read (word.txt) and then fill the words ArrayList up with the words from the file. The countWords method should accept an integer that represents...

  • 1. Copy the file secret.txt into a path that you can access. Read FilePath.doc if you...

    1. Copy the file secret.txt into a path that you can access. Read FilePath.doc if you have questions on file path. Copy SecretMessage.java into your NetBeans or other IDE tools. 2. Finish the main method that will read the file secret.txt, separate it into word tokens.You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. These letters should converted to capitals, then be appended to StringBuffer object to...

  • This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = '...

    This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = ' '; private static final char UPPER_BOUND = '_'; private static final int RANGE = UPPER_BOUND - LOWER_BOUND + 1; /** * This method determines if a string is within the allowable bounds of ASCII codes * according to the LOWER_BOUND and UPPER_BOUND characters * @param plainText a string to be encrypted, if it is within the allowable bounds * @return true if all characters...

  • Please Explain the following question in detail so that I can understand how to solve it:...

    Please Explain the following question in detail so that I can understand how to solve it: Assume that you want to use both an input file called "myinput.txt" and an output file called "myoutput.txt" which are located in a folder called "mydata" on the g: drive. In the program below, fill in all the missing details so that you can read a series of values (one by one) from the input file into the variable "num". Continue to read values...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT