Lambda, stream

Source: Internet
Author: User

 

Lambda  1. Lambda expression Concept

A Lambda expression is an anonymous function and can be understood as a piece of code that can be passed (that is, the function is passed like data ).

Lambda expressions require the support of functional interfaces (that is, interfaces with only one abstract method.

Lambda OPERATOR:->. The operator with the same arrow splits the lambda expression into two sides,

Here, the list of parameters for writing lambda expressions on the left (parameters of abstract methods in the interface); the function for writing lambda expressions on the right (implementation of abstract methods), that is, the lambda body.

 

2. Basic Syntax of lambda expressions

Syntax:

(Parameters)-> Expression

Or

(Parameters)-> {statements ;}

 

3. Basic writing

Let's take a look at a few simple examples of lambda expressions:

// 1. No parameter is required. The returned value is 5.

()-> 5

// 2. Receive a parameter (number type) and return a value of 2 times

X-> 2 * x

// 3. Accept two parameters (numbers) and return their difference

(X, y)-> x-y

// 4. receive two integer integers and return their sum

(Integer x, integer y)-> X + Y

// 5. Accept a String object and print it on the console. No value is returned (it looks like void is returned)

(String S)-> system. Out. Print (s)

 

Through the above several simple examples, we will summarize the basic syntax of lambda expressions:

1). The left type can be left-side;

2) when there is only one parameter on the left side, parentheses can also be omitted;

3) when there is only one statement on the right, both braces and return can be omitted;

4) there are multiple statements on the right, which must contain braces.

 

4. Lambda expressions are used in a for loop.

String [] names = {"Mike", "Mary", "Eric", "Lucy", "Rose "};

List <string> students = arrays. aslist (names );

// Previous cycle method

For (string student: Students ){

System. Out. Print (student + ";");

}

// Method 1: Use lambda expressions and functions

Students. foreach (student)-> system. Out. Print (student + ";"));

// Method 2: Use the double colon operator (the first syntax format referenced by the lambda expression method, which will be described below)

Students. foreach (system. Out: println );

 

5. Lambda expression method reference (double colon operator)

When the content in the lambda body has been implemented by a method, you can use the method reference. There are three syntax formats:

1) object: instance method name

For example, consumer <string> con = (x)-> system. Out. println (x); can be written:

Consumer <string> con = system. Out: println; // system. out is the printwriter object.

2) Class: static method name

For example, comparator <integer> COM = (x, y)-> integer. Compare (x, y); can be written:

Comparator <integer> COM = integer: Compare;

3) Class: instance method name

For example, bipredicate <string, string> BP = (x, y)-> X. Equals (y );

Bipredicate <string, string> BP = string: equals;

Note: Only when the first parameter in the lambda parameter list is the caller of the instance method, and the second parameter is the parameter of the instance method, you can use the 3rd syntax format class :: instance method name. For example, in the preceding example, the first parameter X is the caller of the instance method X. Equals (Y), and the second parameter Y is the parameter of the method.

 

Stream 1. Stream acquisition

1) Get from collection

List <integer> List = new arraylist <integer> (arrays. aslist (1, 2, 4, 5 ));

 

Stream <integer> stream = List. Stream ();

2) Get Through Array

String [] array = {"are", "you", "OK "};

 

Stream <string> stream = array. Stream (array );

// Process the basic type array

Int [] array = {1, 2, 3, 4, 5 };

 

// Arrays. Stream (array) obtains an intstream object.

Stream <integer> stream = arrays. Stream (array). Boxed ();

3) obtain the value (this method has a defect)

Stream <string> stream = stream. Of ("are", "you", "OK ");

 

2. Filter

The filter function receives a Lambda expression as a parameter, which returns a Boolean value. During execution, the stream sends elements to the filter one by one and filters out the elements whose execution result is true;

// Filter out non-empty items in the list

 

List <string> List = arrays. aslist ("are", "you", "", "OK ");

 

List <string> filted = List. Stream ()

. Filter (X->! X. Empty ())

. Collect (collectors. tolist ());

 

3. deduplication, truncation, and skipping

Deduplicate distinct:

List <string> List = arrays. aslist ("are", "you", "you", "OK ");

List <string> distincted = List. Stream ()

. Distinct ()

. Collect (collectors. tolist ());

The first n elements of the intercepted stream:. Limit (3)

The first n elements of the hop over-current:. Skip (2)

 

4. Map

Each element in the stream executes a function to convert the element to another type of output. The stream delivers each element to the map function, executes the lambda expression in the map, and finally stores the execution result in a new stream.

For example, convert each integer type element in the list to the string type after auto-increment.

List <integer> List = arrays. aslist (1, 2, 3, 4, 5 );

 

List <string> result = List. Stream ()

. Map (X-> string. valueof (++ X ))

. Collect (collectors. tolist ());

 

5. Merge multiple stream flatmap

List <string> list1 = .....

List <string> list2 =...

List <list <string> List = arrays. aslist (list1, list2 );

 

// Combine list1 and list2 in the list into a list <string>

List <string> listsum = List. Stream ()

. Flatmap (list: Stream)

. Collect (collectors. tolist ());

 

 

The following example shows how to list different words in the list.

List <string> List = new arraylist <string> ();

List. Add ("I am a boy ");

List. Add ("I love the girl ");

List. Add ("but the girl loves another girl ");

 

List. Stream (). Map (line-> line. Split ("") // word segmentation for each item and map it to an array

// Combine each sub-item array into the mainstream to form a total number of streams containing all sub-item Arrays

. Flatmap (Arrays: Stream)

. Distinct (); // deduplication

. Foreach (system. Out: println); // print

 

6. Matching Element

1) match any element: anymatch

2) match all elements: allmatch

3) does not match all elements: nonematch

 

7. Get Elements

1) obtain any element: findany

2) obtain the first element: findfirst

Optional object Introduction

Optional is a newly added container of Java 8. This container only stores one or zero elements. It is used to prevent nullpointexception. It provides the following methods:

  • Ispresent () determines whether there is a value in the container.
  • If the ifpresent (consume lambda) container is not empty, execute the lambda expression in brackets.
  • T get () gets the elements in the container. If the container is empty, a nosuchelement exception is thrown.
  • T orelse (t other) gets the elements in the container. If the container is empty, the default values in the brackets are returned.

 

8. traverse the stream foreach

The foreach method traverses each element in the stream. The parameter is a Lambda expression used to perform operations on each traversal element;

// Output 10 random numbers

Random random = new random ();

Random. ints (). Limit (10). foreach (system. Out: println );

 

Lambda, stream

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.