The new features of Java 8 are so easy to use!!



During the interview, I was asked about the new features of Java 8 and forgot a lot,Organized the knowledge about the new features of Java 8If there is something wrong, please correct it. Let’s swim in the ocean of knowledge

The new features of Java 8 are so easy to use!!

1. Lambda expression

Lambda expressions areAn anonymous function(this is not entirely true for Java, but let’s put it this way now). In short, it is a method without declaration, that is, it has no access modifier, return value declaration and name.

We always pass function functions to methods through anonymous classes. The following is the old version of event listening Code:

someObject.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            //Event listener implementation goes here...

In the above example, in order to add custom code to the mouse listener, we define an anonymous inner class mousealdapter and create its object. In this way, we pass some functions to the addMouseListener method.

In Java, it is not easy to pass common methods or functions as parameters. Therefore, Java 8 adds a new language level feature called lambda expression.

1.1 functional interface

Note that if you want to use lambda expressions, you must use a functional interface. If you use a functional interface, there can only be one abstract method in the interface

Lambda in Java can't appear alone, it needs a functional interface to flourish. Lambda expression method body is actually the implementation of function interface

give an example:

package com.yztcedu.lambdademo_01;
@Functionalinterface // after adding this annotation, there can only be one abstract method in the interface.
public interface A {
    void call();

1.2 lambda syntax

It includes three parts
1. A comma separated formal parameter in parentheses. The parameter is the parameter of the method in the functional interface
2. An arrow symbol: - >
3. Method bodies, which can be expressions and code blocks

(parameters) – > expression or (parameters) – > {statements;}

Runnable runnable = () ->  System.out.println ("this is a thread implemented with ramda");

If you don’t use lambda expressions, this is the case:

Runnable runnable = new Runnable() {
            public void run() {
                System.out.println ("this is a thread implemented with an inner class");

1.3 method reference

In fact, it is a simplified way of lambda expression. The referenced method is actually the method body implementation of lambda expression, and the syntax is very simple. On the left is the container (which can be the class name and instance name), in the middle is “::”, and on the right is the corresponding method name. As follows:

Classname:: methodname for static methods. For example, object:: equals
If it is an instance method, it is instance:: methodname. For example, object obj = new object (); obj:: equals;
Constructor. Is classname:: new
Runnable runnable = Demo2::run;

public static void run(){
        System.out.println ("code of method reference...);

1.4 default method interface improvement

In short, an interface can have an implementation method, and it doesn't need an implementation class to implement its method. Just add the default keyword before the method name.
package com.yztcedu.lambdademo_01;
public interface A {
    void call();
    default void fun() {
        System.out.println ("I am the code in default method 1 of the interface");
    default void fun2() {
        System.out.println ("I'm the code in the default method 2 of the interface");

Why do you have this feature? First of all, the previous interface is a double-edged sword. The advantage is that it is oriented to abstraction rather than concrete programming,When you need to modify the interface, you need to modify all the classes that implement the interface

2. Stream data stream

In the traditional programming method before java8, if we need to operate a set data, we need to use the API provided by the set to obtain the elements of the set through a loop. This way of accessing data will make the code appear bloated. The newly introduced stream class in java8 is used to encapsulate the set data again. By using stream instead of traversing the common set array, list and map Operation can greatly improve efficiency

We can vividly understand that the operation of stream is to process a group of rough handicraft prototypes (i.e. the corresponding stream data source) into uniform color handicraft (i.e. the final result). The first step is to select the appropriate prototype (i.e. the filter of the corresponding stream) The second step is to color the selected prototypes (corresponding to the map method of the stream), and the third step is to remove the lustrous prototypes (corresponding to the “collect (tolist ()) method of the stream). The operations before removing the handicraft are all intermediate operations. There can be multiple or zero intermediate operations, but each stream data source can only have one termination operation, otherwise the program will report an error.

Actual project operation code:

class Employee {
    Private long empno; // employee number
    Private string ename; // employee name
    Private integer salary; // salary
    Private integer deptno; // department number
    //The get / set method, construction method and toString method are omitted here
Employee e1 = new Employee(7369L, "SMITH", 800, 20);
Employee e2 = new Employee(7499L, "ALLEN", 1600, 30);
Employee e3 = new Employee(7521L, "WARD", 1250, 30);
Employee e4 = new Employee(7782L, "CLARK", 2450, 10);
Employee e5 = new Employee(7876L, "ADAMS", 1100, 20);

List<Employee> employees = Arrays.asList(e1, e2, e3, e4, e5);
Foreach method
Foreach method用于迭代stream流中的每一个元素;

Implementation results:

Employee{empno=7369, ename=’SMITH’, salary=800, deptno=20}
Employee{empno=7499, ename=’ALLEN’, salary=1600, deptno=30}
Employee{empno=7521, ename=’WARD’, salary=1250, deptno=30}
Employee{empno=7782, ename=’CLARK’, salary=2450, deptno=10}
Employee{empno=7876, ename=’ADAMS’, salary=1100, deptno=20}

Map method
//The map method is used to map the data in the stream one to one according to the custom rules
//Get the names of all employees
List<String> enames = -> employee.getEname()).collect(Collectors.toList());;
Implementation results:


Starting from Java 8, using the new API of ArrayList and lambda expression, we can write as follows:

list.forEach(e -> System.out.println(e));

In fact, the lambda expression here just passes parameters to the println() method without doing anything else


That’s it.

System.out Is a reference to a printstream instance; System.out : println is a reference to an instance method
The reference also specifies the( System.out )And the reference to the method (printstream:: println)
System.out : println is not System.out.println  The former is a method reference expression, while the latter cannot be used as an expression alone, but must be followed by a parameter list surrounded by parentheses to form a method call expression.
System.out : println can be regarded as a lambda expression e - > System.out.println (e) The abbreviation of.
Common stream operations

The new features of Java 8 are so easy to use!!

1. Collect (tolist()) terminates the operation

A list can be generated from the values in the stream, or a set set can be generated from collect (toset()).

Example: take each string in the stream and put it in a new list

    public void collectToList() {
        String[] testStrings = { "java", "react", "angular", "vue" };
        List<String> list = Stream.of(testStrings).collect(Collectors.toList());
        for (int i = 0, length = list.size(); i < length; i++) {

The new features of Java 8 are so easy to use!!

2. Map intermediate operation

By mapping one type of value to another type of value, each value in the stream can be mapped to a new value and finally converted to a new stream.

Example: convert every string in the stream to uppercase,

    public void mapTest() {
        String[] testStrings = { "java", "react", "angular", "vue" };
        List<String> list = Stream.of(testStrings).map(test -> test.toUpperCase()).collect(Collectors.toList());
        list.forEach(test -> System.out.println(test));

3. Filter intermediate operation
Traverse and filter out the elements that meet the conditions to form a new stream.

Example: to filter out the number of elements starting with J, the count method in this example is also a termination operation, in order to calculate the number of elements in the stream

    public void filterTest() {
        List<String> list = Arrays.asList("java", "react", "angular", "javascript", "vue");
        long count = -> p.startsWith("j")).count();

There are many more waysI don’t want to list more. You can find out what you like by yourself

The new features of Java 8 are so easy to use!!

It’s not easy to create. If this article can help you, please give me your support. Give me a rose, a fragrance in my hand, and I’ll be happy with you

Recommended Today

How to Build a Cybersecurity Career

Original text:How to Build a Cybersecurity Career How to build the cause of network security Normative guidelines for building a successful career in the field of information security fromDaniel miesslerstayinformation safetyCreated / updated: December 17, 2019 I’ve been doing itinformation safety(now many people call it network security) it’s been about 20 years, and I’ve spent […]