Home Java Javagetting Started Detailed introduction to new features of JDK8

Detailed introduction to new features of JDK8

Nov 26, 2019 pm 01:45 PM
jdk8 new features

Detailed introduction to new features of JDK8

Functional programming

Object-oriented emphasizes that "everything is an object". If you want to do something, you must find an object to do it with. Functional programming ideas emphasize "what to do" rather than "how to do it".

Ordinary opening thread

// 匿名内部类对象
Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("乌鸦坐飞机");
    }
};
new Thread(task).start();
Copy after login

More java related free video tutorials: java online tutorial

Function Open a thread using programming like

new Thread(() -> System.out.println("龙卷风摧毁停车场")).start();
Copy after login

The parentheses in front of it: method parameters. If there are no parameters, write (). The arrow points to what is to be done later. Behind the arrow is like a method body brace, which represents the specific What to do.

Lambda expression

Lambda expression, also known as closure, is the most important new feature driving the release of Java 8.

Lambda allows functions to be used as parameters of a method (functions are passed into methods as parameters). Using lambda expressions can make your code more concise and compact.

Three elements: parameters, arrows, code

Format: (parameter type parameter name) -> {some code}

Use Lambda expression The premise of the formula: there must be an interface and there is only one abstract method in the interface

Demonstration: write a Cook interface, there is a makeFood() method in the interface

public static void main(String[] args) {
    method(() -> {
        System.out.println("闪刀启动!");
    });
}
 
private static void method(Cook cook) {
    cook.makeFood();
}
Copy after login

Lambda expression Formula omission rules:

The parameter type can be omitted. But you can only omit the types of all parameters at the same time, or not omit them at all. If there is one and only one parameter, then the parentheses can be omitted. If there is one and only one statement within the braces, then regardless of whether there is a return value, return, braces Parentheses and semicolons can be omitted.

    public static void main(String[] args) {
        method((a, b)-> a + b);
    }
 
    private static void method(Calculator calculator) {
        int result = calculator.sum(1234, 9876);
        System.out.println(result);
    }
Copy after login

When new an interface, you can also use lambda expressions instead of anonymous inner classes

Runnable task = () -> System.out.println("闪刀启动!");
new Thread(task).start();
Copy after login

Functional interface

The interface has and There is only one abstract method, called a functional interface.

The annotation @FunctionalInterface has been added to JDK8, which is used to detect whether an interface is a functional interface. If it is not a functional interface, an error will be reported during compilation. The @FunctionalInerface annotation is optional. Even if this annotation is not used, as long as the interface meets the definition requirements of a functional interface, it is still a functional interface.

@FunctionalInterface
public interface MyInterface {
    void method();
}
Copy after login

Method reference

Printer printer = (str) -> System.out.println(str);This code actually Can be abbreviated.

As long as it is deducible, it is referenceable, so passing parameters is actually meaningless, so here you can actually use method references to abbreviate System.out::println

Starting from java8, a new operator is introduced, the method reference operator (two colons written consecutively), the expression is a method reference, the essence of method reference and Lambda is exactly the same, the purpose is to simplify Lambda expression style of writing.

How to write Lambda: s->System.out.println(s)

How to write method reference: System.out::println

The two writing methods are completely equivalent

 
    public static void main(String[] args) {
        method(System.out::println);
    }
 
    private static void method(Printer printer) {
        printer.print("hello");
    }
Copy after login

Interface

default method

The interface is originally Two abstract methods now need to be turned into three abstract methods. At this time, its implementation class also needs to implement new methods.

When there are too many implementation classes, it is very troublesome to operate. The JDK used to use the open-close design mode: open for extensions and closed for modifications. That is: create a new interface, inherit the original interface, and define new methods. However, in this case, the original implementation classes do not have new methods. At this time, the interface default method can be used.

The keyword is modified with default, and the method requires a method body. All subclasses of such a method will be implemented by default (you don’t have to write it yourself). If you want to override it, you can also override it in the implementation class

/**
 * 从java8开始,接口当中允许定义default默认方法
 * 修饰符:public default(public可以省略,default不能省略)
 */
public interface MyInterface {
 
    void method1();
 
    void method2();
 
    default void methodNew() {
        System.out.println("接口默认方法执行");
    }
 
}
Copy after login

Note: The default method in the interface is equivalent So a new keyword and the "default" of the four modifiers are not the same concept.

Using the default keyword can make the program achieve the effect of "multiple inheritance".

static method

Starting from java8, static methods are allowed to be defined in interfaces, and their usage is the same as static methods of general classes.

public interface Animal {
 
    void eat();
 
    static Animal getAnimal() {
        return new Cat();
    }
}
Copy after login

Streaming operation

The first impression that streaming processing gives developers is that it makes collection operations much simpler. Usually we need multiple lines of code to complete it. The operation can be implemented in one line with the help of streaming processing.

For example, if we want to filter out all even numbers from a collection containing integers and encapsulate them into a new List for return, then before java8, we need to implement the following code:

For a collection of nums:

List<Integer> evens = new ArrayList<>();
for (final Integer num : nums) {
    if (num % 2 == 0) {
        evens.add(num);
    }
}
Copy after login

Through Java8’s streaming processing, we can simplify the code to:

List<Integer> evens = nums.stream().filter(num -> num % 2 == 0).collect(Collectors.toList());
Copy after login

Let’s briefly explain the meaning of the above line of statement, stream() operation Convert the collection into a stream, filter() performs our custom filtering process, here we filter out all even numbers through lambda expressions, and finally we encapsulate the results through collect() and specify them through Collectors.toList() Encapsulated into a List collection and returned.

常用操作案例:

        //初始化list集合
        List<String> list = new ArrayList<String>();
        list.add("测试数据1");
        list.add("测试数据2");
        list.add("测试数据3");
        list.add("测试数据12");
        
        //使用λ表达式遍历集合
        list.forEach(s -> System.out.println(s));
        
        //结合Predicate使用和过滤条件筛选元素
        Predicate<String> contain1 = n -> n.contains("1");
        Predicate<String> contain2 = n -> n.contains("2");
        
        //根据条件遍历集合
        list.stream().filter(contain1).forEach(n -> System.out.println(n));
        list.stream().filter(s -> contain1.test(s)).forEach(s -> System.out.println(s));
        list.stream().filter(contain1.and(contain2)).forEach(n -> System.out.println(n));
        list.stream().filter(contain1.or(contain2)).forEach(n -> System.out.println(n));
        
        //将过滤后的元素重新放到一个集合中
        List<String> newList = list.stream().filter(contain1.and(contain2)).collect(Collectors.toList());
        
集合中decimal求和
		BigDecimal sum = list
				.stream()
				.map(Person::getAmount)
				.reduce(BigDecimal::add)
				.get();
 
//排序 , 也需要新的集合接收
	List<Student> resultList = new ArrayList<Student>();
	resultList = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList())
Copy after login

推荐java相关文章:java零基础入门

欢迎大家一起来学习!

The above is the detailed content of Detailed introduction to new features of JDK8. 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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

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

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

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.

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

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

New Redis extension introduced in PHP8.1 New Redis extension introduced in PHP8.1 Jul 07, 2023 pm 09:41 PM

The new Redis extension introduced in PHP8.1 With the rapid development of the Internet, a large amount of data needs to be stored and processed. In order to improve the efficiency and performance of data processing, caching has become an indispensable part. In PHP development, Redis, as a high-performance key-value storage system, is widely used in caching and data storage scenarios. In order to further improve the experience of using Redis in PHP, PHP8.1 introduces a new Redis extension. This article will introduce the new functions of this extension and provide

What are the new features of go language? What are the new features of go language? Aug 24, 2023 pm 01:36 PM

The new features of go language are: 1. Go module, used to manage the dependencies of Go language projects; 2. Error handling, adding a new error type error, making error handling more flexible and concise; 3. Context package, used Used to transfer request range values ​​between goroutines; 4. Embedding, that is, one structure can be embedded in another structure; 5. Synchronization package, to better control the synchronization and communication between goroutines; 6. Error value, Better distinguish between different types of errors; 7. Generics allow developers to write more flexibly.

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