Interface AccountService{
public void createAccount();
}
AccountService accountServiceAnonymous = new AccountService(){
public void createAccount(){
Account account = new Account();
save(account);
}
};
AccountService accountServiceLambda = () -> {
Account account = new Account();
save(account);
}
Apart from reduced number of lines of code, are there any other advantages of using lambda expressions in java 8 ?
解决方案
Adding to what @Bilbo has mentioned in comments. In Java 1.7 there was a new JVM Opcode was released named invokedynamic and Java 8 Lambda uses this. So the following code will result in an Anonymous class being created when you compile the code. Possible $1.class so if you have 10 anonymous classes that is 10 more classes in the final jar.
AccountService accountServiceAnonymous = new AccountService(){
public void createAccount(){
Account account = new Account();
save(account);
}
};
But Java 8 lambda uses invokedynamic to call lambdas thus if you have 10 lambdas it will not result in any anonymous classes thus reducing the final jar size.
AccountService accountServiceLambda = () -> {
Account account = new Account();
save(account);
}