Java 8

Lambda expressions

[optional] With explicit data types:

String[] names = directory.list((File dir, String name) -> name.endsWith(".java"));

Block syntax

String[] names = directory.list((File dir, String name) -> {
    return name.endsWith(".java")
});

Method references

Advantage over lambda:

  • shorter

  • includes the names of the class containing the method => easier to read

Syntax

  • object::instanceMethod (e.g. System.out::println, equivalent x -> System.out.println(x))

  • Class::staticMethod (e.g. Math::max, equivalent (x,y) -> Math.max(x,y))

  • Class::instanceMethod invoke a method on a reference to an object supplied by the context (e.g. String::length, equivalent x -> x.length())

Constructor reference

Based on the context in lambda expression => constructor with String arg is used.

Copy constructor

💡 Useful if you want to isolate original instances.

Using copy constructor it is possible to break that connection.

To Array

Functional interfaces

all methods are public => no need to specify deliberately

Methods from Object don't count against the single abstract method limit (e.g. Comparator is still functional interface).

java.util.function

Consumer

How andThen method works:

Interface

single abstract method

IntConsumer

void accept(int x)

DoubleConsumer

void accept(double x)

LongConsumer

void accept(long x)

BiConsumer

void accept(T t, U u)

Supplier

Interface

Single abstract method

IntSupplier

int getAsInt()

DoubleSupplier

double getAsDouble()

LongSupplier

long getAsLong()

BooleanSupplier

boolean getAsBoolean()

Use case:

  • concept of deferred execution

Predicate

💡 You can have a method which has a parameter of Predicate type.

💡 Can be a good idea to have frequently used predicates as a constants.

💡 It is possible to combine predicates using default methods:

Function

Transforms input parameter of type T to output of type R

If (T == R) => UnaryOperator;

BiFunction

if (R == T == U) => BinaryOperator (e.g. Math.max)

Stream

Stream is a sequence of elements that does not save elements or modify the original source

Streams do not process any data until a terminal expression is reached

Terminal operations: anyMatch(), allMatch(), noneMatch(), count(), collect(), findAny(), forEach(),...

Create streams

IntStream, LongStream, DoubleStream

Boxed streams

Reduction operations

Reduce method:

Most general form of reduce

Consider a Book class, the goal is to create a Map<Integer, Book> from List<Book>

Debugging streams with peak

returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as they are consumed from the resulting stream.

Converting Strings to stream

Last updated

Was this helpful?