Lambda Expressions Lambda expressions Detailed Detailed

Lambda expressions Detailed

 


Category:  the JDK new features undefined

 

About Lambda

Lambda expressions are a new feature JDK8 can replace most of the anonymous inner class, write Java code more elegant, especially through the collection and other collections operations, can greatly optimize code structure.

JDK also provides a number of built-in functions for our use interface, making use of Lambda expressions are more convenient and efficient.

Requirements for interfaces

Although the use of Lambda expressions can be simple to achieve certain interfaces, but not all of the interfaces can be implemented using Lambda expressions. Lambda specified interface only one method needs to be implemented, not only have a specified interface method

In jdk 8 has another new feature: default, the default will be the default implementation of the modified method, the method must not be implemented, it does not affect the use of Lambda expressions.

@FunctionalInterface

Modifying functional interface, the abstract method requires only one interface. This annotation will always be together and lambda expressions.

Lambda basic grammar

We here are six interfaces, later all operations using the six interface to elaborate.

/**多参数无返回*/
@FunctionalInterface
public interface NoReturnMultiParam { void method(int a, int b); } /**无参无返回值*/ @FunctionalInterface public interface NoReturnNoParam { void method(); } /**一个参数无返回*/ @FunctionalInterface public interface NoReturnOneParam { void method(int a); } /**多个参数有返回值*/ @FunctionalInterface public interface ReturnMultiParam { int method(int a, int b); } /*** 无参有返回*/ @FunctionalInterface public interface ReturnNoParam { int method(); } /**一个参数有返回值*/ @FunctionalInterface public interface ReturnOneParam { int method(int a); } 

Grammatical form of () -> {}, where () is used to describe the parameter list, {} is used to describe a method thereof, -> is the lambda operator, as read (goes to).

import lambda.interfaces.*;

public class Test1 { public static void main(String[] args) { //无参无返回 NoReturnNoParam noReturnNoParam = () -> { System.out.println("NoReturnNoParam"); }; noReturnNoParam.method(); //一个参数无返回 NoReturnOneParam noReturnOneParam = (int a) -> { System.out.println("NoReturnOneParam param:" + a); }; noReturnOneParam.method(6); //多个参数无返回 NoReturnMultiParam noReturnMultiParam = (int a, int b) -> { System.out.println("NoReturnMultiParam param:" + "{" + a +"," + + b +"}"); }; noReturnMultiParam.method(6, 8); //无参有返回值 ReturnNoParam returnNoParam = () -> { System.out.print("ReturnNoParam"); return 1; }; int res = returnNoParam.method(); System.out.println("return:" + res); //一个参数有返回值 ReturnOneParam returnOneParam = (int a) -> { System.out.println("ReturnOneParam param:" + a); return 1; }; int res2 = returnOneParam.method(6); System.out.println("return:" + res2); //多个参数有返回值 ReturnMultiParam returnMultiParam = (int a, int b) -> { System.out.println("ReturnMultiParam param:" + "{" + a + "," + b +"}"); return 1; }; int res3 = returnMultiParam.method(6, 8); System.out.println("return:" + res3); } } 

Lambda simplified syntax

We can be done to further simplify the code by observing the following code to write more elegant code.

 
import lambda.interfaces.*;

public class Test2 { public static void main(String[] args) { //1.简化参数类型,可以不写参数类型,但是必须所有参数都不写 NoReturnMultiParam lamdba1 = (a, b) -> { System.out.println("简化参数类型"); }; lamdba1.method(1, 2); //2.简化参数小括号,如果只有一个参数则可以省略参数小括号 NoReturnOneParam lambda2 = a -> { System.out.println("简化参数小括号"); }; lambda2.method(1); //3.简化方法体大括号,如果方法条只有一条语句,则可以胜率方法体大括号 NoReturnNoParam lambda3 = () -> System.out.println("简化方法体大括号"); lambda3.method(); //4.如果方法体只有一条语句,并且是 return 语句,则可以省略方法体大括号 ReturnOneParam lambda4 = a -> a+3; System.out.println(lambda4.method(5)); ReturnMultiParam lambda5 = (a, b) -> a+b; System.out.println(lambda5.method(1, 1)); } } 

Lambda expressions commonly used example

  • lambda expressions reference method

Sometimes we do not have to rewrite their own method of an anonymous inner classes, we can use the interface lambda expressions quickly directed to a method that has already been achieved.

grammar

:: attribution method by method name belonger static method for the class name, common ownership by targeting method

 
public class Exe1 {
    public static void main(String[] args) { ReturnOneParam lambda1 = a -> doubleNum(a); System.out.println(lambda1.method(3)); //lambda2 引用了已经实现的 doubleNum 方法 ReturnOneParam lambda2 = Exe1::doubleNum; System.out.println(lambda2.method(3)); Exe1 exe = new Exe1(); //lambda4 引用了已经实现的 addTwo 方法 ReturnOneParam lambda4 = exe::addTwo; System.out.println(lambda4.method(2)); } /** * 要求 * 1.参数数量和类型要与接口中定义的一致 * 2.返回值类型要与接口中定义的一致 */ public static int doubleNum(int a) { return a * 2; } public int addTwo(int a) { return a + 2; } } 
  • Reference to the constructor method

Generally, we need to declare an interface as an object generator by class name :: new way to instantiate an object, then call the method returns an object.

 
interface ItemCreatorBlankConstruct {
    Item getItem(); } interface ItemCreatorParamContruct { Item getItem(int id, String name, double price); } public class Exe2 { public static void main(String[] args) { ItemCreatorBlankConstruct creator = () -> new Item(); Item item = creator.getItem(); ItemCreatorBlankConstruct creator2 = Item::new; Item item2 = creator2.getItem(); ItemCreatorParamContruct creator3 = Item::new; Item item3 = creator3.getItem(112, "鼠标", 135.99); } } 
  • lambda expressions to create a thread

Our previous work by creating a Thread object, and then rewrite the run () method by an anonymous inner classes, a reference to an anonymous inner classes we should think of a lambda expression can be used to simplify the process of creating a thread.

 
    Thread t = new Thread(() -> {
      for (int i = 0; i < 10; i++) { System.out.println(2 + ":" + i); } }); t.start(); 
  • Through the collection

We can call the collection  public void forEach(Consumer<? super E> action) method, elements in the collection to traverse through lambda expressions. The following is a method of traversing Consumer interface and a set of operations. Consumer Interface is a function interface jdk to us.

 
    @FunctionalInterface
    public interface Consumer<T> { void accept(T t); //.... } 
 
      ArrayList<Integer> list = new ArrayList<>();

      Collections.addAll(list, 1,2,3,4,5); //lambda表达式 方法引用 list.forEach(System.out::println); list.forEach(element -> { if (element % 2 == 0) { System.out.println(element); } }); 
  • To delete an element in the collection

We public boolean removeIf(Predicate<? super E> filter)delete an element in the collection method, Predicate jdk is also a function interface we provide, you can simplify the preparation process.

 
      ArrayList<Item> items = new ArrayList<>();
      items.add(new Item(11, "小牙刷", 12.05 )); items.add(new Item(5, "日本马桶盖", 999.05 )); items.add(new Item(7, "格力空调", 888.88 )); items.add(new Item(17, "肥皂", 2.00 )); items.add(new Item(9, "冰箱", 4200.00 )); items.removeIf(ele -> ele.getId() == 7); //通过 foreach 遍历,查看是否已经删除 items.forEach(System.out::println); 
  • Sorting inside a collection of elements

Before us is to sort the elements in the set, it must call the sort method, passing in the Comparator anonymous inner class overrides compare methods, we can now use lambda expressions to simplify the code.

 
        ArrayList<Item> list = new ArrayList<>();
        list.add(new Item(13, "背心", 7.80)); list.add(new Item(11, "半袖", 37.80)); list.add(new Item(14, "风衣", 139.80)); list.add(new Item(12, "秋裤", 55.33)); /* list.sort(new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { return o1.getId() - o2.getId(); } }); */ list.sort((o1, o2) -> o1.getId() - o2.getId()); System.out.println(list); 

Closure problem Lambda expressions

This is something we will be present in the anonymous inner class, if we let go of the Notes will complain, tell me num is the final value can not be changed. Here Although we did not identify the type num is final, but the opportunity to help us add virtual keyword final modification during compilation.

 
import java.util.function.Consumer;
public class Main { public static void main(String[] args) { int num = 10; Consumer<String> consumer = ele -> { System.out.println(num); }; //num = num + 2; consumer.accept("hello"); } } 

Author:  Sea to

Source: https://www.cnblogs.com/haixiang/p/11029639.html

This site uses " CC BY 4.0 " Creative Commons agreement, reproduced in the article clearly indicate the position of the author and source.

 

 
 
 

 

About Lambda

Lambda expressions are a new feature JDK8 can replace most of the anonymous inner class, write Java code more elegant, especially through the collection and other collections operations, can greatly optimize code structure.

JDK also provides a number of built-in functions for our use interface, making use of Lambda expressions are more convenient and efficient.

Requirements for interfaces

Although the use of Lambda expressions can be simple to achieve certain interfaces, but not all of the interfaces can be implemented using Lambda expressions. Lambda specified interface only one method needs to be implemented, not only have a specified interface method

In jdk 8 has another new feature: default, the default will be the default implementation of the modified method, the method must not be implemented, it does not affect the use of Lambda expressions.

@FunctionalInterface

Modifying functional interface, the abstract method requires only one interface. This annotation will always be together and lambda expressions.

Lambda basic grammar

We here are six interfaces, later all operations using the six interface to elaborate.

/**多参数无返回*/
@FunctionalInterface
public interface NoReturnMultiParam { void method(int a, int b); } /**无参无返回值*/ @FunctionalInterface public interface NoReturnNoParam { void method(); } /**一个参数无返回*/ @FunctionalInterface public interface NoReturnOneParam { void method(int a); } /**多个参数有返回值*/ @FunctionalInterface public interface ReturnMultiParam { int method(int a, int b); } /*** 无参有返回*/ @FunctionalInterface public interface ReturnNoParam { int method(); } /**一个参数有返回值*/ @FunctionalInterface public interface ReturnOneParam { int method(int a); } 

Grammatical form of () -> {}, where () is used to describe the parameter list, {} is used to describe a method thereof, -> is the lambda operator, as read (goes to).

import lambda.interfaces.*;

public class Test1 { public static void main(String[] args) { //无参无返回 NoReturnNoParam noReturnNoParam = () -> { System.out.println("NoReturnNoParam"); }; noReturnNoParam.method(); //一个参数无返回 NoReturnOneParam noReturnOneParam = (int a) -> { System.out.println("NoReturnOneParam param:" + a); }; noReturnOneParam.method(6); //多个参数无返回 NoReturnMultiParam noReturnMultiParam = (int a, int b) -> { System.out.println("NoReturnMultiParam param:" + "{" + a +"," + + b +"}"); }; noReturnMultiParam.method(6, 8); //无参有返回值 ReturnNoParam returnNoParam = () -> { System.out.print("ReturnNoParam"); return 1; }; int res = returnNoParam.method(); System.out.println("return:" + res); //一个参数有返回值 ReturnOneParam returnOneParam = (int a) -> { System.out.println("ReturnOneParam param:" + a); return 1; }; int res2 = returnOneParam.method(6); System.out.println("return:" + res2); //多个参数有返回值 ReturnMultiParam returnMultiParam = (int a, int b) -> { System.out.println("ReturnMultiParam param:" + "{" + a + "," + b +"}"); return 1; }; int res3 = returnMultiParam.method(6, 8); System.out.println("return:" + res3); } } 

Lambda simplified syntax

We can be done to further simplify the code by observing the following code to write more elegant code.

 
import lambda.interfaces.*;

public class Test2 { public static void main(String[] args) { //1.简化参数类型,可以不写参数类型,但是必须所有参数都不写 NoReturnMultiParam lamdba1 = (a, b) -> { System.out.println("简化参数类型"); }; lamdba1.method(1, 2); //2.简化参数小括号,如果只有一个参数则可以省略参数小括号 NoReturnOneParam lambda2 = a -> { System.out.println("简化参数小括号"); }; lambda2.method(1); //3.简化方法体大括号,如果方法条只有一条语句,则可以胜率方法体大括号 NoReturnNoParam lambda3 = () -> System.out.println("简化方法体大括号"); lambda3.method(); //4.如果方法体只有一条语句,并且是 return 语句,则可以省略方法体大括号 ReturnOneParam lambda4 = a -> a+3; System.out.println(lambda4.method(5)); ReturnMultiParam lambda5 = (a, b) -> a+b; System.out.println(lambda5.method(1, 1)); } } 

Lambda expressions commonly used example

  • lambda expressions reference method

Sometimes we do not have to rewrite their own method of an anonymous inner classes, we can use the interface lambda expressions quickly directed to a method that has already been achieved.

grammar

:: attribution method by method name belonger static method for the class name, common ownership by targeting method

 
public class Exe1 {
    public static void main(String[] args) { ReturnOneParam lambda1 = a -> doubleNum(a); System.out.println(lambda1.method(3)); //lambda2 引用了已经实现的 doubleNum 方法 ReturnOneParam lambda2 = Exe1::doubleNum; System.out.println(lambda2.method(3)); Exe1 exe = new Exe1(); //lambda4 引用了已经实现的 addTwo 方法 ReturnOneParam lambda4 = exe::addTwo; System.out.println(lambda4.method(2)); } /** * 要求 * 1.参数数量和类型要与接口中定义的一致 * 2.返回值类型要与接口中定义的一致 */ public static int doubleNum(int a) { return a * 2; } public int addTwo(int a) { return a + 2; } } 
  • Reference to the constructor method

Generally, we need to declare an interface as an object generator by class name :: new way to instantiate an object, then call the method returns an object.

 
interface ItemCreatorBlankConstruct {
    Item getItem(); } interface ItemCreatorParamContruct { Item getItem(int id, String name, double price); } public class Exe2 { public static void main(String[] args) { ItemCreatorBlankConstruct creator = () -> new Item(); Item item = creator.getItem(); ItemCreatorBlankConstruct creator2 = Item::new; Item item2 = creator2.getItem(); ItemCreatorParamContruct creator3 = Item::new; Item item3 = creator3.getItem(112, "鼠标", 135.99); } } 
  • lambda expressions to create a thread

Our previous work by creating a Thread object, and then rewrite the run () method by an anonymous inner classes, a reference to an anonymous inner classes we should think of a lambda expression can be used to simplify the process of creating a thread.

 
    Thread t = new Thread(() -> {
      for (int i = 0; i < 10; i++) { System.out.println(2 + ":" + i); } }); t.start(); 
  • Through the collection

We can call the collection  public void forEach(Consumer<? super E> action) method, elements in the collection to traverse through lambda expressions. The following is a method of traversing Consumer interface and a set of operations. Consumer Interface is a function interface jdk to us.

 
    @FunctionalInterface
    public interface Consumer<T> { void accept(T t); //.... } 
 
      ArrayList<Integer> list = new ArrayList<>();

      Collections.addAll(list, 1,2,3,4,5); //lambda表达式 方法引用 list.forEach(System.out::println); list.forEach(element -> { if (element % 2 == 0) { System.out.println(element); } }); 
  • To delete an element in the collection

We public boolean removeIf(Predicate<? super E> filter)delete an element in the collection method, Predicate jdk is also a function interface we provide, you can simplify the preparation process.

 
      ArrayList<Item> items = new ArrayList<>();
      items.add(new Item(11, "小牙刷", 12.05 )); items.add(new Item(5, "日本马桶盖", 999.05 )); items.add(new Item(7, "格力空调", 888.88 )); items.add(new Item(17, "肥皂", 2.00 )); items.add(new Item(9, "冰箱", 4200.00 )); items.removeIf(ele -> ele.getId() == 7); //通过 foreach 遍历,查看是否已经删除 items.forEach(System.out::println); 
  • Sorting inside a collection of elements

Before us is to sort the elements in the set, it must call the sort method, passing in the Comparator anonymous inner class overrides compare methods, we can now use lambda expressions to simplify the code.

 
        ArrayList<Item> list = new ArrayList<>();
        list.add(new Item(13, "背心", 7.80)); list.add(new Item(11, "半袖", 37.80)); list.add(new Item(14, "风衣", 139.80)); list.add(new Item(12, "秋裤", 55.33)); /* list.sort(new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { return o1.getId() - o2.getId(); } }); */ list.sort((o1, o2) -> o1.getId() - o2.getId()); System.out.println(list); 

Closure problem Lambda expressions

This is something we will be present in the anonymous inner class, if we let go of the Notes will complain, tell me num is the final value can not be changed. Here Although we did not identify the type num is final, but the opportunity to help us add virtual keyword final modification during compilation.

 
import java.util.function.Consumer;
public class Main { public static void main(String[] args) { int num = 10; Consumer<String> consumer = ele -> { System.out.println(num); }; //num = num + 2; consumer.accept("hello"); } } 

Guess you like

Origin www.cnblogs.com/lqmblog/p/12551254.html