6.3 lambda expressions, 6.3 lambda

Source: Internet
Author: User

6.3 lambda expressions, 6.3 lambda

6.3.1 A lambda expression is a piece of code that can be passed. It can be executed once or multiple times later.

Think (how to complete the work at a specified interval and put the work in the actionreceivmed method of an ActionListener :)

class Worker implements ActionListener{    public void actionPerformed(ActionEvent event )    {      //do some work      }}

To execute this code repeatedly, You can construct an instance of the Worker class and submit the instance to a Timer object. The focus here is that the actionreceivmed method contains the code that you want to execute later.

Think (how to sort with a custom comparator. To sort strings by length rather than the default dictionary order, you can input a Comparator object to the sort method :)

class lengthComparator implements Comparator<String>{    public int compare(String first,String second)    {        return first.length()-second.length();    }}...Arrays.sort(strings,new lengthComparator());

In common: It is to pass a code block to an object (one is a timer or an sort method ). This code will be called at a certain time in the future.

6.3.2 lambda expression syntax

(String first, String second)
-> First. length ()-second. length ()

This is the first lambda expression I have seen. A lambda expression is a code block and the variable specification of the Code must be passed in.

-------- Expressions with parameter variables are called Lambda expressions.

------------------------- Expression form, parameter, arrow (->), and an expression. If the code to be computed cannot be placed in an expression, put the code in {} and contain the displayed return statement. For example:

(String first,String second)->{     if(first.length()<second.length()) return -1;else if (first.length()>second.length())  return 1;else return 0;}

Even if the lambda expression does not have a parameter, empty parentheses are required, just like the method without parameters:

( ->) {for(int i=100;i>=0;i--) System.out.println(i); }

 

If you can export the parameter type of a lambda expression, you can ignore its type. For example:

Comparator<String> comp        =(first,second)            ->first.length()>second.length();

 

If the method has only one parameter and the type of this parameter can be deduced, parentheses can be omitted;

ActionListener listener =event->       System.out.println("The time is "+new Data()); 

 

You do not need to specify the return type of the lambda expression. The return type of a lambda expression is always derived from the context. For example:

(String first,String second)->first.length()-second.length()

The above can be used in the context where int type results are required.

The following example shows how to use a lambda expression in a comparator and an action listener.

 1 package cc.openhome; 2 import java.awt.Toolkit; 3 import java.util.Arrays; 4 import java.util.Date; 5 import javax.swing.JOptionPane; 6 import javax.swing.Timer; 7 public class LambdaTest { 8     public static void main(String[] args) { 9         // TODO code application logic here10         String[] planets =new String[] {"Yi","Er","San","Si","Wu","Liu","Qi","Ba"};11         System.out.println(Arrays.toString(planets));12         System.out.println("Sortd in dictionary order:");13         Arrays.sort(planets);14         System.out.println(Arrays.toString(planets));15         System.out.println("Sorted by length:");16         Arrays.sort(planets,(first,second) -> first.length()-second.length());17         System.out.println(Arrays.toString(planets));18         Timer t =new Timer (1000,event -> {System.out.println("The time is "+new Date());Toolkit.getDefaultToolkit().beep();});19         t.start();20          JOptionPane.showMessageDialog(null, "Quit programe?");21     }  22 }
[Yi, Er, San, Si, Wu, Liu, Qi, Ba] Sortd in dictionary order: [Ba, Er, Liu, Qi, San, Si, Wu, yi] Sorted by length: [Ba, Er, Qi, Si, Wu, Yi, Liu, san] The time is Wed Mar 21 10:00:34 CST 2018The time is Wed Mar 21 10:00:35 CST 2018The time is Wed Mar 21 10:00:36 CST 2018The time is Wed Mar 21 10:00:37 CST 2018The time is Wed Mar 21 10:00:38 CST 2018The time is Wed Mar 21 10:00:39 CST 2018The time is Wed Mar 21 10:00:40 CST 2018The time is Wed Mar 21 10:00:41 CST 2018 successful build (total time: 8 seconds)
Run:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.