Java Reference
In-Depth Information
use a custom ordering. Although the sort command supports command-line parameters to
perform various predefined kinds of sorting such as reverse order, these are limited.
For example, let's say you have a collection of invoice IDs with format similar to 2013UK0001,
2014US0002, .... The first four digits represent the year, the next two letters a country code, and
last four digits the ID of a client. You may want to sort these invoice IDs by year or perhaps
using the customer ID or even the country code. What you really want is the ability to tell the
sort command to take as an argument an ordering defined by the user: a separate piece of code
passed to the sort command.
Now, as a direct parallel in Java, you want to tell a sort method to compare using a customized
order. You could write a method compareUsingCustomerId to compare two invoice IDs but,
prior to Java 8, you couldn't pass this method to another method! You could create a
Comparator object to pass to the sort method as we showed at the start of this chapter, but this
is verbose and obfuscates the idea of simply reusing an existing piece of behavior. Java 8 adds
the ability to pass methods (your code) as arguments to other methods. Figure 1.3 , based on
figure 1.2 , illustrates this idea. We also refer to this conceptually as behavior parameterization .
Why is this important? The Streams API is built on the idea of passing code to parameterize the
behavior of its operations, just as you passed compareUsingCustomerId to parameterize the
behavior of sort.
Figure 1.3. Passing method compareUsingCustomerId as an argument to
sort
We summarize how this works in section 1.2 of this chapter but leave full details to chapters 2
and 3 . Chapters 13 and 14 look at more advanced things you can do using this feature, with
techniques from the functional programming community.
 
Search WWH ::




Custom Search