Why add a lambda expression to Java?

Source: Internet
Author: User

Lambda expressions, also known as closures, are very popular in many modern programming languages. Among the many different reasons, one of the most urgent reasons for the Java platform is that lambda expressions can simplify the distributed processing of collections on multithreading. List and set are representative. When the client code gets an iterator from the set, it uses the iteration and rotation of elements to retrieve and process them. If different elements are processed in parallel, the client code has the responsibility to organize them. In Java 8, the purpose is to replace the functions provided by the set, get the functions, and use them to process elements in different ways (we will use a very simple function forEach as an example, it gets a function and applies to any element) the advantage is to transform the collection to iterate internally and organize those elements, and transfer the parallel code from the client to the library code. However, a simple method is required to provide a function for the collection function to allow the client code to gain an advantage here. The standard method is to create an anonymous class to implement the corresponding interface. However, the syntax for defining internal anonymous classes is too clumsy. For example, in the forEach function set, an instance of the Block interface is obtained and Its apply function is called as any element. Interface Block <T> {void apply (T t);} Suppose we want to use forEach to replace the coordinates of x and y on the Point element (Java. awt. Point) in the List. Using the internal Anonymous class to implement the Block, we change the function, like this: pointList. forEach (new Block () {public void apply (Point p) {p. move (p. y, p. x) ;}}); however, with Lambda, you can write pointList. forEach (p-> p. move (p. y, p. x ));

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.