国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java Javagetting Started Preliminary learning of new features of java 1.8

Preliminary learning of new features of java 1.8

Feb 26, 2021 am 10:06 AM
new features

Preliminary learning of new features of java 1.8

The Java 8 release is the most revolutionary version since Java 5 released in 2004. Java 8 brings a lot of new features to the Java language, compilers, class libraries, development tools and JVM.

This article introduces several new features in Java 1.8 in detail, hoping to help everyone.

1. Lambda expression

Format: (parameter) -> {code segment}

For example: new Thread(() -> {System.out. println("hello world!")}).start(); This is the lambda expression.

The implementation of lambda needs to rely on functional interfaces. Lambda is essentially an anonymous inner class. Before jdk1.8, if the method needs to operate the implementation method of other interfaces, it can be achieved through anonymous inner classes.

After jdk1.8, anonymous inner classes can be replaced by lambda expressions, and it is more simplified.

package java8;
 
public class LambdaDemo {
	
	public static void main(String[] args) {
		//JDK1.8之前使用接口,采用匿名內(nèi)部類的方式
		MyInterface mi = new MyInterface() {
			@Override
			public void test() {
				System.out.println("test");
			}
		};
		
		mi.test();
		
		//JDK1.8之后,使用lambda表達(dá)式
		MyInterface lmi = () -> {
			System.out.println("test");
		};
		
		lmi.test();
	}
}
//定義一個(gè)函數(shù)式接口,只有一個(gè)抽象方法 
interface MyInterface{
	
	void test();
}

Functional interface: An interface with one and only one abstract method is called a functional interface

The common interfaces of functional interfaces, Function, Predicate, Supplier, and Consumer, are all in java.util.

Function interface under function package: R apply(T t) receives a parameter and returns an object

package java8;
 
import java.util.function.Function;
 
public class LambdaDemo {
 
	public static void main(String[] args) {
		// function的使用
		// 傳統(tǒng)模式,第一個(gè)泛型:接收的參數(shù)類型 第二個(gè)泛型,返回的參數(shù)類型
		Function<String, String> function1 = new Function<String, String>() {
			@Override
			public String apply(String t) {
				return t;
			}
		};
		// 調(diào)用apply方法,并獲取返回結(jié)果
		String res1 = function1.apply("function的使用");
		System.out.println(res1);
		// lambda的使用,當(dāng)參數(shù)只有一個(gè)且不寫參數(shù)類型時(shí),"()"可以省略
		Function<String, String> function2 = t -> {
			return t;
		};
		// 調(diào)用apply方法,并獲取返回結(jié)果
		String res2 = function2.apply("function的使用");
		System.out.println(res2);
	}
}

Predicate interface: boolean test(T t) receives a parameter and returns a boolean value

Commonly used for comparison

package java8;
 
import java.util.function.*;
 
public class LambdaDemo {
 
	public static void main(String[] args) {
		// predicate的使用
		// 傳統(tǒng)模式,泛型參數(shù):接收的參數(shù)類型
		Predicate<Integer> predicate1 = new Predicate<Integer>() {
 
			@Override
			public boolean test(Integer t) {
				// 大于等于10就為真,否則為假
				return t >= 10;
			}
 
		};
		// 執(zhí)行predicate1的方法
		System.out.println(predicate1.test(11));
		System.out.println(predicate1.test(8));
		
		
		//使用lambda表達(dá)式
		Predicate<Integer> predicate2 = new Predicate<Integer>() {
			@Override
			public boolean test(Integer t) {
				// 大于等于10就為真,否則為假
				return t >= 10;
			}
		};
		// 執(zhí)行predicate1的方法
		System.out.println(predicate2.test(11));
		System.out.println(predicate2.test(8));
	}
}

Supplier interface: T get() returns an object

The producer of the producer-consumer model only produces objects

package java8;
 
import java.util.function.*;
 
public class LambdaDemo {
 
	public static void main(String[] args) {
		//Supplier的使用
		// 傳統(tǒng)模式,泛型參數(shù):返回的參數(shù)類型
		Supplier<String> s1 = new Supplier<String>() {
 
			@Override
			public String get() {
				return new String("supplier");
			}
		};
		//調(diào)用
		System.out.println(s1.get());
		
		// 使用lambda表達(dá)式
		//當(dāng)代碼只有一句時(shí),可以省略"{}",不接收參數(shù)時(shí),"()"不能省略
		Supplier<String> s2 = () -> new String("supplier");
		System.out.println(s2.get());
	}
}

Consumer interface: accept (T t) receives a parameter and does not return any value

The producer of the producer-consumer model only consumes objects

package java8;
 
import java.util.function.*;
 
public class LambdaDemo {
 
	public static void main(String[] args) {
		// Consumer的使用
		// 傳統(tǒng)模式,泛型參數(shù):返回的參數(shù)類型
		Consumer<String> con1 = new Consumer<String>() {
 
			@Override
			public void accept(String t) {
				System.out.println(t);
			}
		};
		con1.accept("consumer");
		
		//使用lambda表達(dá)式,同時(shí)省略"()","{}"
		Consumer<String> con2 = t -> System.out.println(t);
		con2.accept("consumer");
	}
}

(Learning video sharing:java Video tutorial )

Practical usage of lambda:

package java8;
 
import java.util.function.*;
 
public class LambdaDemo {
 
	public static void main(String[] args) {
		//Runnable的實(shí)現(xiàn),
		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + " run");
		}).start();
		
		System.out.println(Thread.currentThread().getName() + " run");
	}
}

2. Method reference:

Method reference means that there is only one method call in the lambda expression, and this method If there is a real existence, then you can replace the lambda expression with a method reference.

There are four types of method references

Class name::Static method name

Object name::Instance method name

Class name::Instance method Name

Class name::new

package java8;
 
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
 
public class MethodReferenceDemo {
	public static void main(String[] args) {
		// 定義3個(gè)Student對象
		Student s1 = new Student("zhangsan", 90);
		Student s2 = new Student("lisi", 60);
		Student s3 = new Student("wangwu", 70);
		// 添加到集合
		List<Student> students = Arrays.asList(s1, s2, s3);
 
		//普通的lambda實(shí)現(xiàn)
		// sort接收兩個(gè)參數(shù),第一個(gè)參數(shù),要排序的集合,第二個(gè)參數(shù),Comparator接口的實(shí)現(xiàn)
		// Collections.sort(students, (stu1,stu2) -> StudentSortUtil.sortByScore(stu1,stu2));
		// students.forEach(t -> System.out.println(t.getScore()));
 
		// 方法引用1---類名::靜態(tài)方法名
		// Collections.sort(students, StudentSortUtil::sortByScore);
		// students.forEach(t -> System.out.println(t.getScore()));
		
		//創(chuàng)建實(shí)例對象,調(diào)用實(shí)例對象的方法
		StudentSortUtil ssu = new StudentSortUtil();
		
		//普通的lambda實(shí)現(xiàn)
//		Collections.sort(students, (stu1, stu2) -> ssu.sortByScoreInstance(stu1, stu2));
//		students.forEach(t -> System.out.println(t.getScore()));
		
		// 方法引用2---對象名::實(shí)例方法名
//		Collections.sort(students, ssu::sortByScoreInstance);
//		students.forEach(t -> System.out.println(t.getScore()));
		
		/*
		 * 方法引用3---類名::實(shí)例方法名
		 * Student的sortByScore()只有一個(gè)參數(shù),而Comparator的實(shí)現(xiàn)需要兩個(gè)參數(shù),為什么編譯器不報(bào)錯(cuò)?
		 * 這是因?yàn)閟ortByScore是一個(gè)普通方法,要使用這個(gè)方法肯定要有一個(gè)Student類的實(shí)例對象來調(diào)用
		 * 而調(diào)用的這個(gè)方法的對象就作為Comparator的第一個(gè)參數(shù)對象傳遞進(jìn)來
		 * 例String的compareTo()方法,調(diào)用這個(gè)方法首先要有一個(gè)String的實(shí)例對象,
		 * 此處str就是這個(gè)實(shí)例對象,str就作為Comparator的第一個(gè)參數(shù)
		 * "hello"這個(gè)String對象就作為第二個(gè)參數(shù)
		 * String str = new String("str1");
		 * str.compareTo("hello");	
		 */
		Collections.sort(students, Student::sortByScore);
		
		
		//創(chuàng)建一個(gè)新的Student對象,使用lambda表達(dá)式創(chuàng)建
		//不接收參數(shù),返回一個(gè)對象,其實(shí)就是Supplier接口的實(shí)例
		Supplier<Student> su1 = () -> new Student();
		//方法引用4---類名::new
		Supplier<Student> su2 = Student::new;
		
		//BiConsumer是Consumer的擴(kuò)展,可以接受兩個(gè)參數(shù)返回一個(gè)值
		BiConsumer<String, Integer> bc1 = (name,score) -> new Student(name,score);
		//替換上面的lambda表達(dá)式,需要接收兩個(gè)參數(shù),所以調(diào)用的是有參構(gòu)造方法
		BiConsumer<String, Integer> bc2 = Student::new;
		
	}
}
 
//定義一個(gè)學(xué)生實(shí)體類
class Student {
	private String name;
	private int score;
 
	public Student() {
	}
 
	public Student(String name, int score) {
		this.name = name;
		this.score = score;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getScore() {
		return score;
	}
 
	public void setScore(int score) {
		this.score = score;
	}
 
	public int sortByScore(Student stu) {
		return this.getScore() - stu.getScore();
	}
 
	public int sortByName(Student stu) {
		return this.getName().compareTo(stu.getName());
	}
}
 
//定義一個(gè)學(xué)生排序工具類
class StudentSortUtil {
 
	public static int sortByScore(Student stu1, Student stu2) {
		return stu1.getScore() - stu2.getScore();
	}
 
	public static int sortByName(Student stu1, Student stu2) {
		return stu1.getName().compareTo(stu2.getName());
	}
 
	// 普通方法,創(chuàng)建對象才能調(diào)用
	public int sortByScoreInstance(Student stu1, Student stu2) {
		return stu1.getScore() - stu2.getScore();
	}
 
	// 普通方法,創(chuàng)建對象才能調(diào)用
	public int sortByNameInstance(Student stu1, Student stu2) {
		return stu1.getName().compareTo(stu2.getName());
	}
}

3. Stream:

Stream is divided into intermediate operation and termination operation. The intermediate operation will continue to return a new stream and the termination operation Return a result.

If there is only an intermediate operation in a line of code, it will not be executed. It will only be executed when it encounters a termination operation.

package java8;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.stream.Stream;
 
public class StreamDemo {
	
	public static void main(String[] args) {
		//Stream的使用
		
		//創(chuàng)建流,參數(shù)為可變參數(shù)
		Stream<Integer> stream = Stream.of(50,66,88);
		
		//將Stream轉(zhuǎn)化為數(shù)組
		//Object[] array =  stream.toArray();
		//System.out.println(Arrays.toString(array));
		
		//篩選過濾條件,參數(shù)為Predicate,動(dòng)作自己指定,找到大于60的數(shù)
		//流分為中間操作和終止操作,節(jié)點(diǎn)流會繼續(xù)返回一個(gè)流對象,終止操作會返回一個(gè)結(jié)果,
		//只有中間流,代碼不會執(zhí)行,只有遇見終止操作才會執(zhí)行
		//stream.filter((target) -> target > 60).forEach(System.out::println);
		
		//map對數(shù)據(jù)進(jìn)行操作,接收一個(gè)Function實(shí)例 例:對流中的每個(gè)元素都乘以2
		stream.map((t) -> 2 * t).forEach(System.out::println);
		
		//流的無限模式,會對seed一直執(zhí)行UnaryOperator的事件,一般和limit配合使用
		//skip(n)跳過n個(gè)元素,limit(n) 返回n個(gè)元素的流
		Stream.iterate(0, t -> t + 2).skip(2).limit(6).forEach(System.out::println);
		
		//將流轉(zhuǎn)換為集合對象,第一個(gè)參數(shù),傳遞一個(gè)Supplier 最終結(jié)果類型由此提供
		//第二個(gè)參數(shù) BiConsumer() 傳遞兩個(gè)參數(shù),第一個(gè)要操作的集合,第二個(gè)當(dāng)前的流元素
		//第三個(gè)元素BiConsumer() 傳遞兩個(gè)集合,最終合并成一個(gè)集合
		//類似StringBuffer.append()方法
//		stream.collect(() -> new ArrayList<Integer>(),
//				(target,item)-> target.add(item),
//				(result,target)-> result.addAll(target)).forEach(System.out::println);
		//可以使用方法引用簡化
		stream.collect(LinkedList::new,LinkedList::add,LinkedList::addAll);
		
	}
}

Related recommendations: java introductory tutorial

The above is the detailed content of Preliminary learning of new features of java 1.8. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
What are the new features of php8 What are the new features of php8 Sep 25, 2023 pm 01:34 PM

New features of php8 include JIT compiler, type deduction, named parameters, union types, properties, error handling improvements, asynchronous programming support, new standard library functions and anonymous class extensions. Detailed introduction: 1. JIT compiler, PHP8 introduces the JIT compiler, which is an important performance improvement. The JIT compiler can compile and optimize some high-frequency execution codes in real time, thereby improving the running speed; 2. Type derivation , PHP8 introduces the type inference function, allowing developers to automatically deduce the type of variables when declaring variables, etc.

A guide to learn the new features of PHP8 and gain an in-depth understanding of the latest technology A guide to learn the new features of PHP8 and gain an in-depth understanding of the latest technology Dec 23, 2023 pm 01:16 PM

An in-depth analysis of the new features of PHP8 to help you master the latest technology. As time goes by, the PHP programming language has been constantly evolving and improving. The recently released PHP8 version provides developers with many exciting new features and improvements, bringing more convenience and efficiency to our development work. In this article, we will analyze the new features of PHP8 in depth and provide specific code examples to help you better master these latest technologies. JIT compiler PHP8 introduces JIT (Just-In-Time) compilation

PHP 8.3 released: new features at a glance PHP 8.3 released: new features at a glance Nov 27, 2023 pm 12:52 PM

PHP8.3 released: Overview of new features As technology continues to develop and needs change, programming languages ??are constantly updated and improved. As a scripting language widely used in web development, PHP has been constantly improving to provide developers with more powerful and efficient tools. The recently released PHP 8.3 version brings many long-awaited new features and improvements. Let’s take a look at an overview of these new features. Initialization of non-null properties In past versions of PHP, if a class property was not explicitly assigned a value, its value

Interpretation of new features of Go language: making programming more efficient Interpretation of new features of Go language: making programming more efficient Mar 10, 2024 pm 12:27 PM

[Interpretation of new features of Go language: To make programming more efficient, specific code examples are needed] In recent years, Go language has attracted much attention in the field of software development, and its simple and efficient design concept has attracted more and more developers. As a statically typed programming language, Go language continues to introduce new features to improve development efficiency and simplify the code writing process. This article will provide an in-depth explanation of the latest features of the Go language and discuss how to experience the convenience brought by these new features through specific code examples. Modular development (GoModules) Go language from 1

What are the new features of es6 What are the new features of es6 Aug 04, 2023 am 09:54 AM

The new features of es6 are: 1. Block-level scope, where variables can be declared in block-level scope; 2. Arrow function, a new way of declaring functions; 3. Destructuring assignment, a way to extract values ??from an array or object and assign a value to a variable; 4. Default parameters, allowing default values ??to be provided for parameters when defining functions; 5. Extension operators, which can expand arrays or objects and extract elements; 6. Template strings; 7. Classes and modules; 8. Iterators and generators; 9. Promise objects; 10. Modular import and export, etc.

An overview of the new features of CSS3: How to use CSS3 to achieve transition effects An overview of the new features of CSS3: How to use CSS3 to achieve transition effects Sep 09, 2023 am 11:27 AM

Overview of the new features of CSS3: How to use CSS3 to achieve transition effects CSS3 is the latest version of CSS. Among the many new features, the most interesting and practical one should be the transition effect. Transition effects can make our pages smoother and more beautiful during interaction, giving users a good visual experience. This article will introduce the basic usage of CSS3 transition effects, with corresponding code examples. transition-property attribute: Specify the CSS property transition effect that needs to be transitioned

An overview of the new features of CSS3: How to apply CSS3 animation effects An overview of the new features of CSS3: How to apply CSS3 animation effects Sep 09, 2023 am 09:15 AM

Overview of the new features of CSS3: How to apply CSS3 animation effects Introduction: With the development of the Internet, CSS3 has gradually replaced CSS2 as the most commonly used style language in front-end development. CSS3 provides many new features, the most popular of which is animation effects. By using CSS3 animation, you can add stunning interactive effects to web pages and improve user experience. This article will introduce some commonly used animation features of CSS3 and provide relevant code examples. 1. TransitionAnimat

Overview of the new features of CSS3: How to use CSS3 to achieve horizontally centered layout Overview of the new features of CSS3: How to use CSS3 to achieve horizontally centered layout Sep 09, 2023 pm 04:09 PM

Overview of the new features of CSS3: How to use CSS3 to achieve horizontally centered layout In web design and layout, horizontally centered layout is a common requirement. In the past, we often used complex JavaScript or CSS tricks to achieve this. However, CSS3 introduced some new features that make horizontally centered layouts simpler and more flexible. This article will introduce some new features of CSS3 and provide some code examples to demonstrate how to use CSS3 to achieve horizontally centered layout. 1. Use flexbox to layout fle

See all articles