51tutvue88l-_sx358_bo1204203200_

This book gives a concise introduction to the many new features of Java 8 (and a few features of Java 7 that haven’t received much attention) for programmers who are already familiar with Java.

  • Lambda Expressions
    • The principal enhancement in Java 8 is the addition of functional programming constructs to its object-oriented roots.
    • A “lambda expression” is a block of code that you can pass around so it can be executed later, once or multiple times.
    • You can supply a lambda expression whenever an object of an interface with a single abstract method is expected. Such an interface is called a functional interface.
    • The Java API defines a number of very generic functional interfaces in the java.util.function package.
    • You can tag any functional interface with the @FunctionalInterface annotation.
    • Method References
      • The expression System.out::println is a method reference that is equivalent to the lambda expression x -> System.out.println(x).
      • There are three principal cases:
        • object::instanceMethod
        • Class::staticMethod
        • Class::instanceMethod
        • In the third case, the first parameter becomes the target of the method. For example, String::compareToIgnoreCase is the same as (x, y) -> x.compareToIgnoreCase(y).
    • Constructor References
      • Constructor references are just like method references, except that the name of the method is new. For example, Button::new is a reference to a Button constructor.
    • Default Methods
      • allowing interface methods with concrete implementations
      • Default methods put an end to the classic pattern of providing an interface and an abstract class that implements most or all of its methods.
    • As of Java 8, you are allowed to add static methods to interfaces.
  • The Stream API
    • Streams are the key abstraction in Java 8 for processing collections of values and specifying what you want to have done, leaving the scheduling of operations to the implementation.
    • When you work with streams, you set up a pipeline of operations in three stages.
      • You create a stream.
      • You specify intermediate operations for transforming the initial stream into others, in one or more steps.
      • You apply a terminal operation to produce a result. This operation forces the execution of the lazy operations that precede it. Afterwards, the stream can no longer be used.
    • the stream was created with the stream or parallelStream method, Stream.of, Stream.empty().
    • The Stream interface has two static methods for making infinite streams: generate, iterate.
    • An Optional<T> object is either a wrapper for an object of type T or for no object. It is intended as a safer alternative than a reference of type T that refers to an object or null.
      • ifPresent
      • orElse
    • To collect a stream (instead of reduce to single value):
      • List<String> result = stream.collect(Collectors.toList());
      • Set<String> result = stream.collect(Collectors.toSet());
      • TreeSet<String> result = stream.collect(Collectors.toCollection(TreeSet::new));
    • Primitive Type Streams:
      • IntStream, LongStream, and DoubleStream
      • To convert a primitive type stream to an object stream, use the boxed method
    • Parallel Streams
      • The parallel method converts any sequential stream into a parallel one.
      • It is your responsibility to ensure that any functions that you pass to parallel stream operations are threadsafe.
      • Some operations can be more effectively parallelized when the ordering requirement is dropped. By calling the Stream.unordered method, you indicate that you are not interested in ordering.
  • Programming with Lambdas
    • The main reason for using a lambda expression is to defer the execution of the code until an appropriate time.
    • When a lambda expression is executed, make sure to provide any required data as inputs.
    • Choose one of the existing functional interfaces if you can.
      • Table 3–1 Common Functional Interfaces
      • Table 3–2 Functional Interfaces for Primitive Types
    • It is often useful to write methods that return an instance of a functional interface.
    • When you work with transformations, consider how you can compose them.
    • To compose transformations lazily, you need to keep a list of all pending transformations and apply them in the end.
    • If you need to apply a lambda many times, you often have a chance to split up the work into subtasks that execute concurrently.
    • Think what should happen when you work with a lambda expression that throws an exception.
    • When working with generic functional interfaces, use ? super wildcards for argument types, ? extends wildcards for return types.
    • When working with generic types that can be transformed by functions, consider supplying map and flatMap.
  • JavaFX
    • In JavaFX, you put everything you want to show onto a scene.
    • And the scene must reside in a stage.
    • You can attach a listener to the property object.
    • There are two kinds of listeners that can be attached to a property. A ChangeListener is notified when the property value has changed, and an InvalidationListener is called when the property value may have changed.
      • In most situations, that difference is immaterial.
    • binding: automatically updating one property when another one changes.
    • Layout
      • JavaFX SceneBuilder: www.oracle.com/technetwork/java/javafx/overview
      • FXML: The markup language that JavaFX uses to describe layouts
    • JavaFX lets you change the visual appearance of the user interface with CSS
    • Charts: http://docs.oracle.com/javafx/2/charts/chart-overview.htm
  • The New Date and Time API
    • java.time API that is introduced in Java 8 has remedied the flaws of the past and should serve us for quite some time.
    • All java.time objects are immutable.
    • An Instant is a point on the time line (similar to a Date).
    • In Java time, each day has exactly 86,400 seconds (i.e., no leap seconds).
    • A Duration is the difference between two instants.
    • LocalDateTime has no time zone information.
    • TemporalAdjuster methods handle common calendar computations, such as finding the first Tuesday of a month.
    • ZonedDateTime is a point in time in a given time zone (similar to GregorianCalendar).
    • Use a Period, not a Duration, when advancing zoned time, in order to account for daylight savings time changes.
    • Use DateTimeFormatter to format and parse dates and times.
  • Concurrency Enhancements
    • java.util.concurrent.atomic package provided classes for lock-free
      mutation of variables

      • E.g. AtomicLong, LongAdder
    • A ConcurrentHashMap is, of course, threadsafe—multiple threads can add and remove elements without damaging the internal structure. Moreover, it is quite efficient, allowing multiple threads to update different parts of the table concurrently without blocking each other.
    • Parallel Array Operations
      • parallelSort
      • parallelSetAll
    • The java.util.concurrent library provides a Future<T> interface to denote a value of type T that will be available at some point in the future.
    • Unlike a plain Future, a CompleteableFuture has a method thenApply to which you can pass the post-processing function.
  • The Nashorn JavaScript Engine
    • [I skipped this chapter]
  • Miscellaneous Goodies
    • Joining strings with a delimiter is finally easy: String.join(“, “, a, b, c) instead of a + “, ” + b + “, ” + c.
    • Integer types now support unsigned arithmetic.
    • The Math class has methods to detect integer overflow.
    • Use Math.floorMod(x, n) instead of x % n if x might be negative.
    • There are new mutators in Collection (removeIf) and List (replaceAll, sort).
    • Files.lines lazily reads a stream of lines.
    • Files.list lazily lists the entries of a directory, and Files.walk traverses them recursively.
    • There is finally official support for Base64 encoding.
    • Annotations can now be repeated and applied to type uses.
      • @NonNull
    • Convenient support for null parameter checks can be found in the Objects class.
  • Java 7 Features That You May Have Missed
    • Use the try-with-resources statement with any object that implements AutoCloseable.
    • The try-with-resources statement rethrows the primary exception if closing a resource throws another exception.
    • You can catch unrelated exceptions with a single catch clause.
    • The exceptions for reflective operations now have a common superclass ReflectiveOperationException.
    • Use the Path interface instead of the File class.
    • You can read and write all characters, or all lines, of a text file with a single command.
    • The Files class has static methods for copying, moving, and deleting files, and for creating files and directories.
    • Use Objects.equals for null-safe equality testing.
    • Objects.hash makes it simple to implement the hashCode method.
    • When comparing numbers in a comparator, use the static compare method.
    • Applets and Java Web Start applications continue to be supported in corporate environments, but they may no longer be viable for home users.
    • Everyone’s favorite trivial change: “+1” can now be converted to an integer without throwing an exception.
    • Changes in ProcessBuilder make it simple to redirect standard input, output, and error streams.

Leave a comment