Java Reference
In-Depth Information
Figure 4.2. Filtering a menu using a stream to find out three
high-calorie dish names
filter —Takes a lambda to exclude certain elements from the stream. In this case, you select dishes
that have more than 300 calories by passing the lambda d ->d.getCalories()> 300 .
map —Takes a lambda to transform an element into another one or to extract information. In this case,
you extract the name for each dish by passing the method reference Dish::getName , which is
equivalent to the lambda d -> d.getName() .
limit —Truncates a stream to contain no more than a given number of elements.
collect —Converts a stream into another form. In this case you convert the stream into a list. It looks
like a bit of magic; we describe how collect works in more detail in chapter 6 . At the moment, you can
see collect as an operation that takes as an argument various recipes for accumulating the elements of
a stream into a summary result. Here, toList() describes a recipe for converting a stream into a list.
Notice how the code we just described is very different than what you'd write if you were to
process the list of menu items step by step. First, you use a much more declarative style to
process the data in the menu where you say what needs to be done: “Find names of three
 
Search WWH ::




Custom Search