Java Reference
In-Depth Information
StreamForker.Results results = new StreamForker<Dish>(menuStream)
.fork("shortMenu", s -> s.map(Dish::getName)
.collect(joining(", ")))
.fork("totalCalories", s -> s.mapToInt(Dish::getCalories).sum())
.fork("mostCaloricDish", s -> s.collect(reducing(
(d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2))
.get())
.fork("dishesByType", s -> s.collect(groupingBy(Dish::getType)))
.getResults();
String shortMenu = results.get("shortMenu");
int totalCalories = results.get("totalCalories");
Dish mostCaloricDish = results.get("mostCaloricDish");
Map<Dish.Type, List<Dish>> dishesByType = results.get("dishesByType");
System.out.println("Short menu: " + shortMenu);
System.out.println("Total calories: " + totalCalories);
System.out.println("Most caloric dish: " + mostCaloricDish);
System.out.println("Dishes by type: " + dishesByType);
The StreamForker provides a convenient, fluent API to fork a stream and assign a different
operation to each forked stream. These operations are expressed in terms of functions applied
on the stream and can be identified by any arbitrary object; in this case we've chosen to use
Strings. When you have no more forks to add, you can invoke getResults on the StreamForker to
trigger the execution of all the defined operations and obtain StreamForker.Results. Because
these operations are internally performed asynchronously, the getResults method returns
immediately, without waiting for all the results to be available.
You can obtain the result of a specific operation by passing the key used to identify it to the
StreamForker.Results interface. If in the meantime the computation of that operation completes,
the get method will return the corresponding result; otherwise, it will block until such a result
isn't available.
As expected, this piece of code generates the following output:
Short menu: pork, beef, chicken, french fries, rice, season fruit, pizza, prawns, salmon
Total calories: 4300
Most caloric dish: pork
 
Search WWH ::




Custom Search