Java Reference
In-Depth Information
Figure 3.2. Tasks A and B are surrounded by the same redundant code
responsible for preparation/cleanup.
3.3.1. Step 1: Remember behavior parameterization
This current code is limited. You can read only the first line of the file. What if you'd like to
return the first two lines instead or even the word used most frequently? Ideally, you'd like to
reuse the code doing setup and cleanup and tell the processFile method to perform different
actions on the file. Does this sound familiar? Yes, you need to parameterize the behavior of
processFile. You need a way to pass behavior to processFile so it can execute different behaviors
using a BufferedReader.
Passing behavior is exactly what lambdas are for. So what should the new processFile method
look like if you wanted to read two lines at once? You basically need a lambda that takes a
BufferedReader and returns a String. For example, here's how to print two lines of a
BufferedReader:
String result = processFile((BufferedReader br) ->
br.readLine() + br.readLine());
 
Search WWH ::




Custom Search