Java Reference
In-Depth Information
nominal currency. In pre-lambda Java, even a simple use case like this is cumbersome to
implement, as shown in the following listing.
Listing 6.1. Grouping transactions by currency in imperative style
If you're an experienced Java developer, you'll probably feel comfortable writing something like
this, but you have to admit that it's a lot of code for such a simple task. Even worse, this is
probably harder to read than to write! The purpose of the code isn't immediately evident at first
glance, even though it can be expressed in a straightforward manner in plain English: “Group a
list of transactions by their currency.” As you'll learn in this chapter, you can achieve exactly the
same result with a single statement by using a more general Collector parameter to the collect
method on Stream rather than the toList special case used in the previous chapter:
Map<Currency, List<Transaction>> transactionsByCurrencies =
transactions.stream().collect(groupingBy(Transaction::getCurrency));
The comparison is quite embarrassing, isn't it?
6.1. Collectors in a nutshell
The previous example clearly shows one of the main advantages of functional-style
programming over an imperative approach: you just have to formulate the result you want to
obtain the “what” and not the steps you need to perform to obtain it—the “how.” In the previous
example, the argument passed to the collect method is an implementation of the Collector
interface, which is a recipe for how to build a summary of the elements in the Stream. In the
previous chapter, the toList recipe just said “Make a list of each element in turn”; in this
example, the groupingBy recipe says “Make a Map whose keys are (currency) buckets and whose
values are a list of elements in those buckets.”
 
Search WWH ::




Custom Search