12 Lambda Expressions

and Streams

Learning Outcomes

  1. Write a statement lambda

  2. Write an expression lambda


Exam Topics

  • Implement functional interfaces using lambda expressions, including interfaces from the java.util.function package

  • Use Java Streams to filter, transform and process data

  • Perform decomposition and reduction, including grouping and partitioning on sequential and parallel streams

  • Use local variable type inference, including as lambda parameters

Oracle Academy

  • No Oracle Academy this week

Textbook

  • 17 Java SE 8 Lambdas and Streams

Tutorial / Practice Activity

  • Lambda Practice

Lesson Plan

  • Mindfulness

  • Previous week review

    • Functional interface implementation

      • Anonymous class

  • Resource reinforcement and clarification

  • Lambda Expressions

    • you can consider lambda expressions as anonymous methods

    • pass functionality as an argument to another method

    • can replace an anonymous inner class method

  • Discussion: Compare and contrast functional programming and object-oriented programming.

  • AWS Lambda - same word, different but somewhat related concept

  • Project

    • Database

Mindfulness

Lambda Interface Implementation

Review the original interface on the bottom of the Encapsulation page. It had this code

interface MyInterface {


public void printIt(String text);

}

and

class MyInterfaceImplementation implements MyInterface {

@Override

public void printIt(String text) {

System.out.println(text);

}

}


MyInterfaceImplementation mii = new MyInterfaceImplementation();

mii.printIt("Lame way");

Review the anonymous interface implementation on the bottom of the Lists page.

It had this code:

MyInterface mi2 = new MyInterface() {

public void printIt(String text){

System.out.println(text);

}

};

mi2.printIt("Anonymous way");

Code written using an anonymous interface implementation can be converted to a lambda expression using the format: parameters, arrow, body. Wild!

This format (with braces) is called a "statement lambda".

MyInterface mi3 = (String text) -> {

System.out.println(text);

};

mi3.printIt("Cool lambda way");

Parameter type can be omitted. Really Wild!

MyInterface mi4 = (text) -> {

System.out.println(text);

};

mi4.printIt("Cooler way");

When it's just one line, the braces and semicolon can be omitted. Super Wild!

This format (without braces) is called an "expression lambda".

MyInterface mi5 = (text) ->

System.out.println(text);

mi5.printIt("Coolest way");

When a lambda expression takes a single parameter, you can also omit the parentheses. Wild(!)

MyInterface mi6 = text ->

System.out.println(text);

mi6.printIt("Cooler than cool");

When a lambda expression does nothing but call an existing method the expression lambda can be replaced with a method reference. Mind == Blown!

MyInterface mi7 = System.out::println;

mi7.printIt("Ice cold");