" is introduced in Java 8, called the arrow operator, or lambda operator; its function is to separate the front and rear parts."/> " is introduced in Java 8, called the arrow operator, or lambda operator; its function is to separate the front and rear parts.">
search
HomeJavajavaTutorialJava8 new features lambda, functional interface, StreamingAPI

Java8 new features lambda, functional interface, StreamingAPI

Lambda expression

1. It is a simplification of the format of anonymous inner class objects

2.A new one is introduced in Java8 The operator "->" is called the arrow operator, or the lambda operator

3. Its function is to divide the front and rear parts into two parts

4. The left side: represents the Lambda expression. Parameter list (parameters of the abstract method defined in the interface)

5. The right side: represents the method body of the method, Lambda body

Writing syntax format

1 .There are no parameters and no return value

The left parenthesis cannot be omitted, and the right brace can be omitted or not

Java8 new features lambda, functional interface, StreamingAPI

2 .There is one parameter, no return value

There are multiple parameters, no return value

The left bracket may or may not be omitted, the right brace may or may not be omitted

Java8 new features lambda, functional interface, StreamingAPI

3. There are many methods that need to be rewritten in the interface. You need to add curly brackets to multiple sentences

Java8 new features lambda, functional interface, StreamingAPI

Note Note: If there is only one statement in the lambda body, the braces can be omitted; if there is only one statement in the brace, and it is a return statement, the return keyword can be omitted

Functional interface

The premise for using Lambda expressions is that the interface must be a functional interface. If there is only one abstract method in the interface, then the interface is a functional interface. A common annotation is To check whether the current interface is a functional interface @FunctionalInterface, if it is not a functional interface, a compilation error will be reported

Function:

What I want to express is the content of a method , since the method is not in any class, all are called functions. What the interface actually wants to express is the declaration of a function. Next, the implementation class object of this interface is used to express the embodiment of a function

Consumption interface:

Abstract method: void accept(T t)

When a function can accept a data and process the data, after the processing is completed, there is no need To return any data, this function needs to be passed as data, so use the consumer interface

package cn.ujiuye.function;
import java.util.function.Consumer;
import cn.ujiuye.domin.Mobile;
/**
 * @author liugang
 * 消费型接口方式
 */
public class CustmoerTest {
     public static void main(String[] args) {
	    Mobile m = new Mobile("华为",3000);
	     //lambad表达式实现赋值  内部显然是对消费者接口的使用,故是对函数式接口编程的新东西
	     updateMobile(m, x -> x.setPrice(x.getPrice() + 1000 ));
	     System.out.println(m);
	 }
    //调用其使用的方法
	private static void updateMobile(Mobile m, Consumer<Mobile> con) {
	     for (int i = 0; i < 3; i++) {
		     con.accept(m);	
		 }
	}
}

Method reference

1. When writing a functional interface, the method Implementation has been implemented by some other object, so there is no need to call this implementation again in Lambda. Instead, you can use the directly defined method

2. Format

Function Functional interface: Name = Object name:: Method name

Functional interface: Name = Class name:: Static method name

3. Function

Treat what has been implemented as A piece of data, as a reference, is assigned to a reference of a functional interface. This reference can be used as the return value of a method, or as an implementation class object

Java8 new features lambda, functional interface, StreamingAPI

StreamingAPI

In jdk1.8, a stream type is provided, which can easily operate the data in the container. Data filtering, output and other operations can be completed without manually defining a loop

Getting the type of Stream and common methods

Getting Collection:

Call the stream() method and call back the Stream object

Termination method: foreach count

Delay method: filter limit skip, etc.

package cn.ujiuye.stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
/**
 * @author liugang
 *
 */
public class StreamApiDemo03Demo03 {
    public static void main(String[] args) {
    	//定义一个集合,并获取stream类型的数据
		List<Integer> list = new ArrayList<Integer>();
		Collections.addAll(list, 12,32,-13,50,100);
		Stream<Integer> stream = list.stream();
		stream.forEach(x ->System.out.println(x - 100));
		System.out.println(list.stream().count());
    }
}

package cn.ujiuye.stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Stream;
/**
 * @author liugang
 * Stream中一些方法的使用
 */
public class StreamApiDemo04 {
   public static void main(String[] args) {
	   ArrayList<Integer> list = new ArrayList<>();
	   Collections.addAll(list, -4,-12,-199,0,15,25,36,100);
	   Stream<Integer> stream = list.stream();
	   stream.filter(x -> x > 0)    //过滤
	         .skip(1)               //跳过
	         .limit(2)              //限制
	         .sorted((x,y) -> -1)   //排序
	         .forEach(System.out::println);
   }
}

Exercise

There are two Arraylist collections that store the names of multiple members in the team. Use the Stream method to perform the following steps

1. The first team only needs the name of the member with a name of 3 characters

2. The first team only needs the first three people after screening

3. The second Teams only need people with the surname Zhang

4. After the second team is screened, the first two people are not required

5. Merge the two teams into one team

6. After the merger Person (custom type) objects of everyone in the team are stored in an ArrayList collection

Team 1: Miyamoto Musashi, Song Gongming, Su Youpeng, Stone Man, Shi Chuanxiang, Li Er, Zhuang Zi, Hong Qigong

Team 2: Pavarotti, Zhang Sanfeng, Zhao Weiwei, Zhang Zizhong, Borzhijin Temujin, Zhang Tianai, Zhang Cuihua

public class StreamApiTest {
    @SuppressWarnings("unused")
	public static void main(String[] args) {
	    //创建集合
    	List<String> list1 = new ArrayList<String>();
	    List<String> list2 = new ArrayList<String>();
	    //把元素添加到集合中
	    Collections.addAll(list1, "宫本武藏","宋公明","苏有朋","石头人","时传祥","李耳","庄子","洪七公");
	    Collections.addAll(list2, "帕瓦罗蒂","张三疯","赵薇薇","张自忠","孛儿只斤铁木真","张天爱","张翠花");
	    //创建Stream对象
	    Stream<String> stream1 = list1.stream();
	    Stream<String> stream2 = list2.stream();
	    //创建筛选后的元素
	    Stream<String> limit1 = stream1.filter(x -> x.length() == 3).limit(3);
	    Stream<String> limit2 = stream2.filter(x -> x.startsWith("张")).skip(2);
	    //将两对的人合到同一个对里
	    Stream<String> concat = Stream.concat(limit1, limit2);
	    //定义一个集合用来存对象
	    List<Person> list = new ArrayList<Person>();
	    //想要的是一个Person对象的流
	    //Stream<Person> map = concat.map(x -> new Person(x);
	    Stream<Person> map = concat.map(Person::new);
	    //将流对象添加到集合中
	    map.forEach(list::add);
	    System.out.println(list);
	}
}

The above is the detailed content of Java8 new features lambda, functional interface, StreamingAPI. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Java 8中如何计算一年前或一年后的日期?Java 8中如何计算一年前或一年后的日期?Apr 26, 2023 am 09:22 AM

Java8计算一年前或一年后的日期利用minus()方法计算一年前的日期packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

如何使用Java 8计算一周后的日期?如何使用Java 8计算一周后的日期?Apr 21, 2023 pm 11:01 PM

Java8如何计算一周后的日期这个例子会计算一周后的日期。LocalDate日期不包含时间信息,它的plus()方法用来增加天、周、月,ChronoUnit类声明了这些时间单位。由于LocalDate也是不变类型,返回后一定要用变量赋值。packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

在Java8中如何获取当前的时间戳在Java8中如何获取当前的时间戳May 01, 2023 am 11:46 AM

在Java8中获取当前的时间戳Instant类有一个静态工厂方法now()会返回当前的时间戳,如下所示:packagecom.shxt.demo02;importjava.time.Instant;publicclassDemo16{publicstaticvoidmain(String[]args){Instanttimestamp=Instant.now();System.out.println("Whatisvalueofthisinstant"+timestamp.t

Java8中如何使用预定义的格式化工具去解析或格式化日期Java8中如何使用预定义的格式化工具去解析或格式化日期Apr 28, 2023 pm 07:40 PM

Java8中如何使用预定义的格式化工具去解析或格式化日期packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;publicclassDemo17{publicstaticvoidmain(String[]args){StringdayAfterTommorrow="20180205";LocalDateformatted=LocalDate.parse

Java8中如何获取年、月、日信息Java8中如何获取年、月、日信息Apr 19, 2023 am 09:49 AM

Java8中获取年、月、日信息packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo02{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();intyear=today.getYear();intmonth=today.getMonthValue();intday=today.getDayOfMonth();System.out.println

Java8中如何判断两个日期是否相等Java8中如何判断两个日期是否相等May 02, 2023 am 08:46 AM

Java8中判断两个日期是否相等packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo04{publicstaticvoidmain(String[]args){LocalDatedate1=LocalDate.now();LocalDatedate2=LocalDate.of(2018,2,5);if(date1.equals(date2)){System.out.println("时间相等");}e

Java8中Clock时钟类怎么用Java8中Clock时钟类怎么用Apr 25, 2023 pm 03:37 PM

Java8的Clock时钟类Java8增加了一个Clock时钟类用于获取当时的时间戳,或当前时区下的日期时间信息。以前用到System.currentTimeInMillis()和TimeZone.getDefault()的地方都可用Clock替换。packagecom.shxt.demo02;importjava.time.Clock;publicclassDemo10{publicstaticvoidmain(String[]args){//Returnsthecurrenttimebase

怎样在Java 8中进行闰年的检查?怎样在Java 8中进行闰年的检查?May 08, 2023 pm 11:16 PM

在Java8中检查闰年packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo14{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();if(today.isLeapYear()){System.out.println("ThisyearisLeapyear");}else{System.out.println("2

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!