Java Reference
In-Depth Information
obtain the sum, average, maximum, and minimum of the calories contained in each dish with a
single summarizing operation:
IntSummaryStatistics menuStatistics =
menu.stream().collect(summarizingInt(Dish::getCalories));
This collector gathers all that information in a class called IntSummaryStatistics that provides
convenient getter methods to access the results. Printing the menu-Statistic object produces the
following output:
IntSummaryStatistics{count=9, sum=4300, min=120,
average=477.777778, max=800}
As usual, there are corresponding summarizingLong and summarizingDouble factory methods
with associated types LongSummaryStatistics and DoubleSummaryStatistics; these are used
when the property to be collected is a primitive-type long or a double.
6.2.3. Joining Strings
The collector returned by the joining factory method concatenates into a single string all strings
resulting from invoking the toString method on each object in the stream. This means you can
concatenate the names of all the dishes in the menu as follows:
String shortMenu = menu.stream().map(Dish::getName).collect(joining());
Note that joining internally makes use of a StringBuilder to append the generated strings into
one. Also note that if the Dish class had a toString method returning the dish's name, you'd
obtain the same result without needing to map over the original stream with a function
extracting the name from each dish:
String shortMenu = menu.stream().collect(joining());
Both produce the following string,
porkbeefchickenfrench friesriceseason fruitpizzaprawnssalmon
which isn't very readable. Fortunately, the joining factory method has an overloaded version
that accepts a delimiter string between two consecutive elements, so you can obtain a
comma-separated list of the dishes' names with
String shortMenu = menu.stream().map(Dish::getName).collect(joining(", "));
 
Search WWH ::




Custom Search