Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 68 java 10 System out println name productInfo name total productInfo total This capability might initially seem like an interesting piece of language trivia that has very little use but it can be handy in certain circumstances Sometimes for example you want to return a few values as an intermediate result inside some method Normally you would need to create and maintain a new class for this purpose just to use it inside a single method For example inside the Collectors averagingDouble implementation a small array of double values is used for this purpose Theres a better approach that you can take with var using an anonymous class as a store for intermediate values Consider a case where you have some products each of which has a name a stock count and a per item monetary worth that is a value associated with it You want to calculate the total cost for each item in other words the count multiplied by the value If that were the only piece of information you had you could just map each product to its cost but to do something useful with the result you would also want the products name The following is an example of how you can do that with var in Java 10 var products List of new Product 10 3 Apple new Product 5 2 Banana new Product 17 5 Pear var productInfos products stream map product new Object String name product getName int total product getStock product getValue
You must have JavaScript enabled to view digital editions.