JAVA 8 Basics

Functional Programming

  • What is functional programming? FP is a paradigm that takes complex computation as the evaluation of mathematical functions (lambda expressions) which makes the code easier to understand, less complex, and reasonable to test. The original Java programming language is based on Von Neumann architecture. The biggest problem of using object-oriented or imperative programming is the mutability and complexity. Functional programming pacifies these problems and works more on expressions than statements. Its concepts are primarily based on immutability (the state cannot be changed) and pure function.
  • All new desktop and laptop computers are multicore computers. The problem is that a classic Java program uses just a single one of these cores, and the power of the others is wasted. Java 8 facilitates new programming styles to better exploit such computers.
  • Functions are first-class values.

Java 8 Features

  • The Streams API

    1. A stream is a sequence of data items that are conceptually produced one at a time
    2. Supports many parallel operations to process data.
    3. It avoids the need for you to write code that uses 'synchronized', which is not only highly error prone but is also more expensive on multicore CPUs.
    4. The addition of Streams in Java 8 can be seen as a direct cause of the two other additions to Java 8:

      • concise techniques to pass code to methods (method references, lambdas)

      • default methods in interfaces.

  • Techniques for passing code to methods

    1. Java 8 adds functions as new forms of value. These facilitate the use of Streams, which Java 8 provides to exploit parallel programming on multicore processors.

    2. File[] hiddenFiles = new File(".").listFiles(File::isHidden);

      • The function isHidden available, so you just pass it to thelistFiles method using the Java 8 method reference :: syntax (meaning “use this method as a value”).

      • Analogously to using an object reference when you pass an object around (created by new), in Java 8 when you write File::isHidden you create a method reference.

  • Lambdas

Passing methods as values is useful, but it’s a bit annoying having to write a definition for short methods such as isHeavyApple and isGreenApple when they’re used perhaps only once or twice. But Java 8 introduces a new notation (anonymous functions, or lambdas) that enables you to write just

filterApples(inventory, (Apple a) -> “green”.equals(a.getColor()) );

or

filterApples(inventory, (Apple a) -> a.getWeight() > 150 );

  • Default methods in interfaces

An interface can now contain method signatures for which an implementing class doesn’t provide an implementation. The missing method bodies are given as part of the interface (hence default implementations).

  • References

journaldev.com/2389/java-8-features-with-ex..