Java 8. Lambdas

  • View
    133

  • Download
    0

Embed Size (px)

Text of Java 8. Lambdas

uchonyy@gmail.comJava 8. Lambdas

Java. The well-known and not well-known

8

lambda-

Java 7Java 8

lambda-(String s) -> { return s. length();}(s) -> { return s. length();}(s) -> s. length()s -> s. length()() -> System.gc();

( Lambda Parameters )->{ Lambda Body }:(int x, int y) -> x+y(x, y) -> x+y(int... x) -> x[0]+1(int[] x) -> x[0]+1

But illegal:(x, int y) -> x+y(x, final y) -> x+y

@FunctionalInterface

RunnableVoidrunSupplierTgetConsumerTVoidacceptBiConsumerT, UVoidacceptFunctionTRapplyBiFunctionT, URapplyUnaryOperatorTTapplyBinaryOperatorT, TTapplyPredicateTBooleantestBiPredicateT,UBooleantest

LongFunctionlongTapplyLongToIntFunctionlongintapplyToLongFunctionTlongapply

:: :: :: :this :: super :: :: new

Lambda noncapturing : Lambda capturing :

Java 7. FinalJava 8. Effectively final

Legal: x y effectively final

void m1(int x) { int y = 1; foo(() -> x+y);}Legal: x y effectively final

void m2(int x) { int y; y = 1; foo(() -> x+y);}Illegal: y effectively final, .void m3(int x) { int y; if (...) y = 1; foo(() -> x+y);}Legal: x y effectively final

void m4(int x) { int y; if (...) y = 1; else y = 2; foo(() ->; x+y);}

Illegal : x effectively final

void m5(int x) { int y; if (...) y = 1; y = 2; foo(() -> x+y);}Illegal: x effectively final

void m6(int x) { foo(() -> x+1); x++;}Illegal : x effectively final

void m7(int x) { foo(() -> x=1);}Illegal : y effectively final

void m8() { int y; foo(() -> y=1);}

Invokedynamic :

:

invokedynamicBootStrap CallSiteMethodHandlepublic Object foo(..){} invokedynamicCallSiteMethodHandlepublic Object foo(..){} MH

Invokedynamic: Printer p = System.out::println; p.print("Str");MethodHandle CallSite,

lambda 1. Lambda noncapturing :

:

class A { public void foo() { List list = ... list.forEach( s -> { System.out.println(s); } ); }} :

class A { public void foo() { List list = ... list.forEach( indy((MH(metaFactory), MH(invokeVirtual Consumer. accepts), MH(invokeStatic A.lambda$1)( ))); } private static void lambda$1(String s) { System.out.println(s); }}

lambda 2. Lambda capturing :

:

class B {public void foo() { List list = ... final int bottom = ..., top = ...; list.removeIf( s -> (s. length() >= bottom && s. length() = bottom && p. length() (s. length() >= bottom && s. length()