Home > Java > Javagetting Started > body text

Detailed introduction to new features of JDK8

王林
Release: 2019-11-26 13:45:05
forward
3020 people have browsed it

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template