New Semester
Started
Get
50% OFF
Study Help!
--h --m --s
Claim Now
Question Answers
Textbooks
Find textbooks, questions and answers
Oops, something went wrong!
Change your search query and then try again
S
Books
FREE
Study Help
Expert Questions
Accounting
General Management
Mathematics
Finance
Organizational Behaviour
Law
Physics
Operating System
Management Leadership
Sociology
Programming
Marketing
Database
Computer Network
Economics
Textbooks Solutions
Accounting
Managerial Accounting
Management Leadership
Cost Accounting
Statistics
Business Law
Corporate Finance
Finance
Economics
Auditing
Tutors
Online Tutors
Find a Tutor
Hire a Tutor
Become a Tutor
AI Tutor
AI Study Planner
NEW
Sell Books
Search
Search
Sign In
Register
study help
computer science
java programming
Big Java, Enhanced Early Objects 7th Edition Cay S Horstmann - Solutions
Using the java.util.function.Predicate interface, write a static generic method:that returns a list of all values for which the predicate returns true. Demonstrate how to use this method by getting a list of all strings with length greater than ten from a given list of strings. Use a lambda
Write a static generic method:that returns a list of the values returned by the function when called with arguments in the values list. List map (List values, Function f)
Write a static generic method:that returns a list of pairs (v, f.apply(v)), where v ranges over the given values. List map (List values, Function f)
Provide expressions that compute the following information about a Stream.a. How many elements start with the letter a?b. How many elements of length greater than ten start with the letter a?c. Are there at least 100 elements that start with the letter a? (Don’t count them all if there are more.)
How can you collect five long words (that is, with more than ten letters) from an ArrayList without using streams? Compare your solution with the code fragment in Section 19.1. Which is easier to understand? Why?
What is the difference between these two expressions? words.filter(w ->w.length() > 10). limit (100).count() words. limit (100).filter(w w.length() >10).count()
Give three ways of making a Stream (or five, including the ones described in Special Topic 19.1).Data from special topic 19.1 Special Topic 19.1 Infinite Streams You can make an infinite stream with the gene rate method. Provide a lambda expression with no arguments, and it is applied for each
How can you place all elements from a Stream intoa. a List?b. an Integer[] array?c. an int[] array?
How do you turn a Stream into a Stream, with each number turned into the equivalent string? How do you turn it back into a Stream?
Give three ways of making a lambda expression that applies the length method to a String (or four if you read Special Topic 19.2).Data from Special Topic 19.2 Special Topic 19.2 Method and Constructor References When a lambda expression consists of just one method call, you can use a very concise
Given an Optional, what are three different ways of printing it when it is present and not printing anything when it isn’t? Which of these can be adapted to print the string "None" if no string is present?
Describe five different ways of producing an IntStream. Which of them can be adapted to producing a DoubleStream?
Suppose you want to find the length of the longest string in a stream. Describe two approaches: using mapToInt followed by the max method of the IntStream class, and calling the max method of Stream. What are the advantages and disadvantages of each approach?
List all terminal operations on object streams and primitive-type streams that have been discussed in this chapter.
List all collectors that were introduced in this chapter.
Explain the values used in the orElse clauses in Section 19.10.2.
Write a program that reads all lines from a file and, using a Stream, prints how many of them contain the word “the”.
Write a program that reads all words from a file and, using a Stream, prints how many of them are the word “the”.
Write a program that reads all lines from a file and, using a Stream, prints all lines containing the word “the”.
Write a program that reads all words from a file and, using a Stream, prints all distinct words with at most four letters (in some order).
Write a method: public static String toString (Stream stream, int n) list of its first n elements. that turns a Stream into a comma-separated
The static getAvailableCurrencies method of the java.util.Currency class yields a set of Currency objects. Turn it into a stream and transform it into a stream of the currency display names.Print them in sorted order.
Write a lambda expression for a function that turns a string into a string made of the first letter, three periods, and the last letter, such as "W...d". (Assume the string has at least two letters.) Then write a program that reads words into a stream, applies the lambda expression to each element,
Write a program that sorts an array of bank accounts by increasing balance. Pass an appropriate lambda expression to Arrays.sort.
Write a program that reads in words from a file and prompts the user for another word. Print the longest word from the file that contains the given word, or "No match"if the word does not occur in the file. Use the max method of Stream.
Write a method:that returns the smallest proper divisor of n or, if n is a prime number, a value indicating that no result is present. public static Optional smallestProperDivisor(int n)
Write a program that reads an integer n and then prints all squares of the integers from 1 to n that are palindromes (that is, their decimal representation equals its reverse). Use IntStream.range, map, and filter.
Write a method public static Stream characters(String str)that yields a stream of strings of length 1 that contains the characters of the string str.Use the codePoints method and skip code points greater than 65535. Extra credit if you don’t skip them and instead produce strings of length 2.
Read all words from a file and print the one with the maximum number of vowels.Use a Stream and the max method. Extra credit if you define the comparator with the Comparator.comparing method described in Special Topic 19.4.
Read all words from a file into an ArrayList, then turn it into a parallel stream.Use the dictionary file words.txt provided with the book’s companion code. Use filters and the findAny method to find any palindrome that has at least five letters, then print the word. What happens when you run the
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.
Read all words in a file and group them by the first letter (in lowercase). Print the average word length for each initial letter. Use collect and Collectors.groupingBy.
Assume that a BankAccount class has methods for yielding the account owner’s name and the current balance. Write a function that, given a list of bank accounts, produces a map that associates owner names with the total balance in all their accounts. Use collect and Collectors.groupingBy.
Write a program that reads a Stream from a file that contains country names and numbers for the population and area. Print the most densely populated country.
Write a function that returns a list of all positions of a given character in a string. Produce two versions— one with streams and one without. Which one is easier to implement?
Find all adjacent duplicates of a Stream, by using a predicate that compares each element against the previous one(stashed away in an array of length 1), updates the array, and returns the result of the comparison. You have to be careful with the first element.
In a stream of random integers, filter out the even ones, call limit(n), and count the result. Set n to 10, 100, 1000, and so on. Measure the amount of time these operations take with a regular stream and a parallel stream. How big does n have to be for parallel streams to be faster on your
Write a program that generates an infinite stream of integers that are perfect squares and then displays the first n of them that are palindromes (that is, their decimal representation equals its reverse). Extra credit if you use BigInteger so that you can find solutions of arbitrary length.
Repeat Exercise •• P19.2 with prime numbers instead of perfect squares.Data from exercise P19.2Write a program that generates an infinite stream of integers that are perfect squares and then displays the first n of them that are palindromes (that is, their decimal representation equals its
Produce an infinite stream that contains the factorials 1!, 2!, 3!, and so on. Hint: First produce a stream containing arrays [1, 1!], [2, 2!], [3, 3!], and so on. Use BigInteger values for the factorials.
Worked Example 19.1 showed you how to find all words with five distinct vowels(which might occur more than once). Using a similar approach, find all words in which each vowel occurs exactly once.Data from worked example 19.1. WORKED EXAMPLE 19.1 Word Propertles It is fun to find words with
Using an approach similar to that in Worked Example 19.1, find all words with length of at least ten in which no letter is repeated. What is the longest one? How many such words exist for each length?Data from worked example 19.1. WORKED EXAMPLE 19.1 Word Propertles It is fun to find words with
Using an approach similar to that in Worked Example 19.1, find all words with exactly one vowel (which might be repeated). What is the longest one? How many such words exist for each length?Data from worked example 19.1. WORKED EXAMPLE 19.1 Word Propertles It is fun to find words with interesting
Perhaps the reason that so many movie titles start with the letter A is that their first word is “A” or “An”? Count how many movies in the data set of Worked Example 19.2 start with these words.Data from worked example 19.2. WORKED EXAMPLE 19.2 A Movie Database In this worked Example, we
What are the 100 most common initial words in movie titles contained in the data set in Worked Example 19.2?Data from worked example 19.2. WORKED EXAMPLE 19.2 A Movie Database In this worked Example, we analyze a large database of movies and use streams to obtain interesting statistics from the
Write a program to determine how many actors there are in the data set in Worked Example 19.2. Note that many actors are in multiple movies. The challenge in this assignment is that each movie has a list of actors, not a single actor, and there is no ready-made collector to form the union of these
Write a program to determine the 100 actors with the most movies, and the number of movies in which they appear. For each movie, produce a map whose keys are the actors, all with value 1. Merge those maps as in Exercise ••• P19.10. Then extract the top 100 actors from a stream of actors.Data
Find an online database with a large number of cities and their locations. Write a program that prints all cities within a given distance from a location. (You will need to find a formula for computing the distance between two points on Earth.)
The ColorFrame in Section 20.5 uses a grid layout manager. Explain a drawback of the grid that is apparent from Figure 15. What could you do to overcome this drawback?Figure 15 box Rectangle x = 5 y 10 width = 20 height 30
Is it a requirement to use inheritance for frames, as described in Section 20.1.3?(Consider Special Topic 20.1.)Data from special topic 20.1 Special Topic 20.1 Adding the main Method to the Frame Class Have another look at the FilledFrame and Filled FrameViewer2 classes. Some programmers prefer to
Why did the program in Section 20.2.2 use a text area and not a label to show how the interest accumulates? How could you have achieved a similar effect with an array of labels?Data from 20.2.2
Add icons to the buttons of Exercise • E20.1. Use a JButton constructor with an Icon argument and supply an ImageIcon.Data from exercise E20.1 Write an application with three buttons labeled “Red”, “Green”, and “Blue” that changes the background color of a panel in the center of the
Write a program that lets users design charts such as the following:Use appropriate components to ask for the length, label, and color, then apply them when the user clicks an “Add Item” button. Golden Gate Brooklyn Delaware Memorial Mackinac
Write a graphical application describing an earthquake, as in Section 5.3. Supply a text field and button for entering the strength of the earthquake. Display the earthquake description in a label.
Modify the slider test program in Section 20.5 to add a set of tick marks to each slider that show the exact slider position.
In the application from Exercise • P20.3, replace the text area with a bar chart that shows the balance after the end of each year.Data from exercise P20.3 Write an application with three labeled text fields, one each for the initial amount of a savings account, the annual interest rate, and
Write a program with a graphical interface that allows the user to convert an amount of money between U.S. dollars (USD), euros (EUR), and British pounds (GBP). The user interface should have the following elements: a text box to enter the amount to be converted, two combo boxes to allow the user
In Exercise •• Business P20.6 , the password is shown as it is typed. Browse the Swing documentation to find an appropriate component for entering a password.Improve the solution of Exercise •• Business P20.6 by using this component instead of a text field. Each time the user types a
What is the difference between an input stream and a reader?
Write a few lines of text to a new PrintWriter("output1.txt", "UTF-8") and the same text to a new PrintWriter("output2.txt", "UTF-16"). How do the output files differ?
How can you open a file for both reading and writing in Java?
What happens if you try to write to a file reader?
What happens if you try to write to a random access file that you opened only for reading? Try it out if you don’t know.
How can you break the Caesar cipher? That is, how can you read a document that was encrypted with the Caesar cipher, even though you don’t know the key?
What happens if you try to save an object that is not serializable in an object output stream? Try it out and report your results.
Of the classes in the java.lang and java.io packages that you have encountered in this book, which implement the Serializable interface?
Why is it better to save an entire ArrayList to an object output stream instead of program ming a loop that writes each element?
What is the file pointer in a file? How do you move it? How do you tell the current position? Why is it a long integer?
How do you move the file pointer to the first byte of a file? To the last byte? To the exact middle of the file?
What happens if you try to move the file pointer past the end of a file? Try it out and report your result.
Can you move the file pointer of System.in?
Paths can be absolute or relative. An absolute path name begins with a root element(/ on Unix-like systems, a drive letter on Windows). Look at the Path API to see how one can create and recognize absolute and relative paths. What does the resolve method do when its argument is an absolute path?
Look up the relativize method in the Path API and explain in which sense it is the opposite of resolve. Give two examples when it is useful; one for files and one for directories.
What exactly does it mean that Files.walk yields the results in depth-first order? Are directory children listed before or after parents? Are files listed before directories?Are either listed alphabetically? Run some experiments to find out.
Write a program that opens a binary file and prints all ASCII characters from that file, that is, all bytes with values between 32 and 126. Print a new line after every 64 characters. What happens when you use your program with word processor documents?With Java class files?
Write a method that reverses all lines in a file. Read all lines, reverse each line, and write the result.
Write a method public static void copy(String infile, String outfile) that copies all bytes from one file to another, without using Files.copy.
Repeat Exercise • E21.3 by using a random access file, reversing each line in place.Data from exercise E21.3Write a method that reverses all lines in a file. Read all lines, reverse each line, and write the result.
Repeat Exercise • E21.3, reading one line at a time and writing the reversed lines to a temporary file. Then erase the original and move the temporary file into its place.Data from exercise E21.3Write a method that reverses all lines in a file. Read all lines, reverse each line, and write the
Modify the BankSimulator program in Section 21.3 so that it is possible to delete an account. To delete a record from the data file, fill the record with zeroes.Data from section 21.3
The data file in Exercise •• E21.6 may end up with many deleted records that take up space. Write a program that compacts such a file, moving all active records to the beginning and shortening the file length. Hint: Use the setLength method of the Random AccessFile class to truncate the file
Enhance the SerialDemo program from Section 21.4 to demonstrate that it can save and restore a bank that contains a mixture of savings and checking accounts.
Write a method that, given a Path to a file that doesn’t yet exist, creates all intermediate directories and the file.
Write a method public static void swap (Path p, Path q) that swaps two files. Use a temporary file.
Random monoalphabet cipher. The Caesar cipher, which shifts all letters by a fixed amount, is far too easy to crack. Here is a better idea. For the key, don’t use numbers but words. Suppose the keyword is FEATHER. Then first remove duplicate let ters, yielding FEATHR, and append the other letters
Letter frequencies. If you encrypt a file using the cipher of Exercise •• P21.1 , it will have all of its letters jumbled up, and will look as if there is no hope of decrypting it without knowing the keyword. Guessing the keyword seems hopeless, too. There are just too many possible keywords.
Vigenère cipher. The trouble with a monoalphabetic cipher is that it can be easily broken by frequency analysis. The so-called Vigenère cipher overcomes this problem by encoding a letter into one of several cipher letters, depending on its position in the input document. Choose a keyword, for
Playfair cipher. Another way of thwarting a simple letter frequency analysis of an encrypted text is to encrypt pairs of letters together. A simple scheme to do this is the Playfair cipher. You pick a keyword and remove duplicate letters from it. Then you fill the keyword, and the remaining letters
Write a program that manipulates a database of product records. Records are stored in a binary file. Each record consists of these items:• Product name: 30 characters at two bytes each = 60 bytes• Price: one double = 8 bytes• Quantity: one int = 8 bytes The program should allow the user to
Implement a graphical user interface for the BankSimulator program in Section 21.3.Data from section 21.3
Write a graphical application in which the user clicks on a panel to add shapes(rect angles, ellipses, cars, etc.) at the mouse click location. The shapes are stored in an array list. When the user selects File->Save from the menu, save the selection of shapes in a file. When the user selects
Write a toolkit that helps a cryptographer decrypt a file that was encrypted using a monoalphabet cipher. A monoalphabet cipher encrypts each character separately.Examples are the Caesar cipher and the cipher in Exercise •• P21.1 . Analyze the letter frequencies as in Exercise • P21.2 . Use
In the BMP format for 24-bit true-color images, an image is stored in binary format.The start of the file has the following information:• The position of the first pixel of the image data, starting at offset 10• The width of the image, starting at offset 18• The height of the image, starting
Write a method public static copyFiles(Path fromDir, Path toDir) that copies all files(but none of the directories) from one directory to another.
Write a method public static copyDirectories(Path fromDir, Path toDir) that copies all files and directories from one directory to another.
Write a method public static clearDirectory(Path dir) that removes all files (but none of the directories) from a directory. Be careful when testing it!
Write a method public static clearAllDirectories(Path dir) that removes all files and all subdirectories from a directory. Be very careful when testing it!
You can use a zip file system to look into the contents of a .zip file. Call FileSystem zipfs = FileSystems.newFileSystem(path, null);where path is the Path to the zip file. Then call zipfs.getPath(p) to get any Path inside the zip file, as if it were a path in a regular directory. You can read,
Run a program with the following instructions: GreetingRunnable r1 = new GreetingRunnable("Hello"); GreetingRunnable r2 = new GreetingRunnable("Goodbye"); r1.run(); r2.run(); Note that the threads don't run in parallel. Explain.
In the program of Section 22.1, is it possible that both threads are sleeping at the same time? Is it possible that neither of the two threads is sleeping at a particular time? Explain.Data from section 22.1
Showing 200 - 300
of 791
1
2
3
4
5
6
7
8
Step by Step Answers