Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.4 Lambdas and streams — a function as a value

Lesson

Implementing an interface concisely

A functional interface is an interface with exactly one abstract method. Instead of writing a whole class to implement it, you can use a lambda expression: parameter -> result. The lambda is an implementation of that one method. You then call it through the interface's method name.


Worked example

interface IntOp { int apply(int x); }

IntOp doubler = x -> x * 2;    // implements apply
IntOp square  = x -> x * x;
System.out.println(doubler.apply(5));   // 10
System.out.println(square.apply(4));    // 16

For more than one parameter, put them in parentheses: (a, b) -> a + b. A lambda lets you pass behavior around like a value.


▶ Try it: run this — two lambdas implement the same interface differently.



A functional interface has...


The lambda x -> x * 2...


Type exactly what this program prints.

interface IntOp { int apply(int x); }
public class Main { public static void main(String[] a){
    IntOp inc = x -> x + 1;
    System.out.println(inc.apply(7));
    System.out.println(inc.apply(0));
}}

A lambda with two parameters is written...


True or false?