Reduction by Java Stream
For business analysis, it is often useful to reduce a list of numbers to a single value. "What is the sum of product A sold among all the invoices?" "What is the median price among all the houses sold in Toronto last month?" "What is the average annual inflation over the last 10 years?" This type of queries is reduction operation that can be handled by the Stream class. Below are some examples to help memorizing how the reduce method is used. Here are three different functions of calculating the sum of a list of integers. The first function is a typical for-loop. The second and third produce the same result by using stream's reduce . Compare the functions for mnemonic. List<Integer> list = Arrays.asList(2, 4, 6, 8, 10, 12, 14, 16); Function<List<Integer>, Integer> sumMethod1 = (numbers) -> { int sum = 0; for (Integer x : numbers) sum += x; return sum; }; System.out.println ( "sum = " + sumMethod1.apply(l...