May 21, 2014

7 useful miscellaneous additions you must know in Java 8

The much awaited addition in Java 8 are Lambda expressions to be used in functional programming and default and static methods in interfaces to support multiple behavior inheritance and helper methods. Here are a few other additional handy additions in Java 8.

Addition #1: String.join( ) method, which is an opposite of String.split(...) was there from pre Java 8.

Addition #2: The Comparator interfaces have a number of useful methods to sort objects with options to nest multiple fields with thenComparing(...), and other handy methods likenullsFirst( ), nullsLast( ), naturalOrder( ),reverseOrder( ), etc. This was made possible as Java 8 interfaces can have default methods (which gives you multiple behavior inheritance) and static methods (a replacement for helper classes).

Addition #3: In Java you cannot simply get rid of the null references that have historically existed, but before Java 8, you need to rely on your code and proper documentation to understand if a reference is optional (i.e can be null) as shown below,

In Java 8, java.util.Optional<T> class has been added to deal with optional object references. The intention with the Optional class is not to replace every null-able reference, but to help in the creation of more robust APIs you could tell if you can expect an optional reference by reading the signature of a method.

The find method signature tells you that it returns a person optionally.

Addition #4: In cases where you want to detect result overflow errors in int and long, the methods addExact, subtractExact, multiplyExact, and toIntExact in Java 8, thejava.lang.Mathclass throws an ArithmeticException when the results overflow. Generally, it is recommended to use BigInteger if you expect large values.