Posts

Finding Median by Stream

Image
This small waterfall is one of the many intermediate operations of the stream. Photo taken in Algonquin, ON The Java's DoubleStream class provides a few methods for common statistics including min(), max(), sum(), and average().  For average(), what does it actually mean?  Here is the description in the specification: The average() method returns an OptionalDouble describing the arithmetic mean of elements of the stream, or an empty optional if the stream is empty. While the arithmetic mean method is handy, we likely want a median method for different needs as well.  The DoubleStream class doesn't provide a median() method but the sorted() method.  We can use the sorted() method to assist in finding the median value. Building the Median Function Given each of existing min(), max(), and average() will return an OptionalDouble, having a median() method to return the same type is preferable.  There are different ways to create a median method, and the goal here is ...

Android UI Design: New vs. Old

Image
A sailboat on Lake Ontario Minimalist design is a sense of calm. Earthquake Track was first released in 2019.  Its user-interface (UI) was built by using some of the modern Material Design components at the time.  In the past decade, UI components were evolving quickly in terms of aesthetic, practicality and programmability.  Such improvements were made possible thanks to better hardware and software.  For mobile device hardware, there were faster processors of multiple cores, and higher screen resolution of Full HD (1920 x 1080 pixels) and way beyond.  These improvements allowed UI components to have beautiful details reacting in parallel smoothly.  For software, the API improvements for app development were substantial.  Those could be seen on screen included many more widget components such as Constraint Layout, Drawer Layout, Card View, and Recycler View.  Those couldn't be seen on screen, such as the Android Jetpack architecture that enabled ...

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...

Useful Java Language Features : Version 11 to 14

For product releases after Java SE 8, Oracle would designate a release, every three years, as a Long-Term-Support (LTS) release. Java SE 11 is an LTS release.  Based on the Oracle Java SE Support Roadmap, Java SE 12 to 15 are non-LTS releases that are more about incremental updates rather than major ones.  At the time of writing, the latest stable Java SE release is version 14.  This release is non-LTS. While the Open JDK community project has their latest release, version 14, available for download,  Amazon offers their latest Corretto JDK, version 11, also for free.  There are other JDK providers offering version 11 and/or 14 as well. Here are some examples to help understanding some of the language features from Java 11 to 14. Java 11: var declaration in Lambda expression // Java 11: var declaration in lambda expression UnaryOperator<Integer> square = (@NonNull var x) -> x * x; // var can be used with annotation such as @NonNull System.out.printl...

Factorial by Different Styles in Java

Here is a collection of methods of calculating factorial by different programming styles. class Factorial { // Iteration static long iterativeFactorial( int n) { long r = 1; for ( int i=1; i<=n; i++) r*=i; return r; } // Recursion static long recursiveFactorial( int n) { return n == 0 ? 1 : n * recursiveFactorial(n-1); } // Tail-recursion static long tailRecurFactorial( int n) { return tailRecurHelper(1L, n); } static long tailRecurHelper( long acc, int n) { return n == 0 ? acc : tailRecurHelper(acc*n, n-1); } // Lambda and Recursion static Function<Integer, Long> lambdaRecurFactorial = x -> x==0 ? 1L : x * Factorial.lambdaRecurFactorial.apply(x-1); // Stream static long streamFactorial ( int n) { return LongStream.rangeClosed(1, n) .reduce(1, (a, b) -> a*b); } /...

Fibonacci Sequence by Modern Java

Fibonacci sequence is one of the well known wonders in mathematics and sciences.  The sequence that captures a type of essence of the universe has always been intriguing.  Below is the code for generating the sequence that the algorithm can be written in an elegant way by modern Java. class Tuple <T, U> { public final T _1; public final U _2; public Tuple(T t, U u) { this ._1 = t; this ._2 = u; } } class Fibonnaci { public static void main(String[] args) { Function<Integer, Stream<Integer>> getFiboStream = (n) -> { Tuple<Integer, Integer> seed = new Tuple<>(1, 1); UnaryOperator<Tuple<Integer, Integer>> f = (x) -> new Tuple<>(x._2, x._1 + x._2); return Stream.iterate(seed, f) .map(x -> x._1) .limit(n); }; String result = getFiboStream.apply(20) ...

Quick Start: Building a RESTful Web Service by Spring Tool Suite

Image
This is an alternative Quick Start tutorial of building a simple RESTful web service.  Instead of offering choices of tools, I have chosen the specific ones. What to Build Part 1: A web service that replies with a greeting; this part is primarily based on the guidance from spring.io Part 2: A web service that replies with an imaginary product price quote; an addition to the original guide Note: The replies, in JSON format, are from Tomcat Required Tools (1) Spring Tool Suite (version 4 in this tutorial) (2) JDK 8 or above (version 13 in this tutorial) PART 1: A web service that replies with a greeting Step 1 Install Spring Tool Suite, and launch it. Step 2 Fill out the New Spring Starter Project form to generate the starter codes. To launch the form: File > New > Spring Starter Project Fill out the two pages of the form as below. Page 1: Notice that Gradle type is chosen for this example. Change project Name, Group, Artifact, and Package to yours...

Parallel Stream Examples

The Stream API allows running in parallel in multiple CPU cores to speed up processing when the algorithm requires a very large number of loops.  Below are some examples that I created as mnemonic and experimental usage. Note that list.stream().parallel() can also be written as list.parallelStream() . Function < Integer , List < Integer >> getList = ( n ) -> { return Stream . iterate ( 1 , i -> i + 1 ) . limit ( n ) . collect ( Collectors . toList ()); }; List < Integer > dataList = getList . apply ( 20 ); // Run in sequence to print dataList . forEach ( x -> System . out . print ( x + " " )); System . out . println (); // Run in parallel to print dataList . stream () . parallel () . forEach ( x -> System . out . print ( x + " " )); System . out . println (); // Run in paraellel to map, collect, and print dataList . stream () ...

Quick Start: Building a Web App by Spring Tool Suite

Image
Small purple plants in springtime There are some examples on spring.io to help developers to get started with using Spring.  While the official Quick Start guide demonstrates a simple way to generate "Hello World", it requires developers to choose their own favorite Integrated Developer Environment (IDE) or lightweight editor, and build the project by Maven at the command prompt.  Here is an alternative Quick Start guide that I have chosen the specific tools. What to build A classic "Hello World!" message replied to a web browser from Tomcat server. What tools are required Spring Tool Suite (version 4 in this example) JDK (version 8 or above) Note: Unlike the official Quick Start guide, installation of Spring Tool Suite but not Maven or Gradle is required. Step 1 Install Spring Tool Suite, and launch it. Step 2 Fill out the New Spring Starter Project form to generate the starter codes. To launch the form: File > New > Spring Starter Proje...

Quick Reference & Example: Optional

Quick Reference Optional is primarily for use as a return type where there is a clear need to prevent Null Pointer Exception.  A variable of type Optional should never itself be null; it should always point to an Optional instance. Methods in the Optional class include: empty, filter, flatMap, get, ifPresent, ifPresentOrElse, isPresent, map, of, ofNullable, or, orElse, orElseGet, orElseThrow, stream An example to demonstrate: flatMap, get, isPresent, map, ofNullable, orElse Imagine that there is a car dealership offering a promotional package for selected car models.  Each Car has a model name and an optional PromoPackage .  Each PromoPackage has a promo name and an optional list of promo items. class PromoPackage { private String promoName; private Optional<List<String>> optItems; PromoPackage (String promoName, Optional<List<String>> optItems) { this .promoName = promoName; this .optItems = optItems...

Strategy Pattern by Lambda Expression - Part 2

Image
Earlier it was mentioned that the restaurant decided to add a veggie burger recipe in their menu.  The veggie burger turned out successful, and the ambitious restaurant owner decided to further expand the food menu by offering a number of pasta dishes. Assume that the developer would need to follow the original Strategy pattern, a concrete class of OperationVeggieBurger would need to be created; similarly for the pasta dishes, a PastaStrategy interface and all the corresponding concrete classes. Imagine that the restaurant would continue expanding the business by adding more food categories, say, Appetizers, Soups, Pizzas, Entrees, Deserts and so on.  The more categories to add, the more food strategy interfaces and the corresponding concrete classes would need to be created. Here is the diagram of the Strategy Pattern that contains BurgerStrategy, PastaStrategy and a potential NewFoodStrategy: Instead of following the original Strategy Pattern, the developer would li...