Su Xiaonuan talks about lambda expressions

It has been a while since Java 8 was released, and the changes in this release are relatively large. Many people compare this change to the upgrade of Java 5. One of the important new features of Java 8 is lambda expressions, which allow us to pass behavior into functions. Come to think of it, before Java 8 we wanted to pass behavior into functions and the only option was anonymous inner classes. After the release of Java8, lambda expressions will largely replace the use of anonymous inner classes , simplifying the code and highlighting the most important part of the original anonymous inner class that contains the real logic code. Especially for students who do data, when they are used to using functional programming languages ​​like scala, the experience will be more profound. Now let's take a look at some common ways of writing lambda expressions in Java 8.

The parameter list and return value type of the calling method in the lambda body should be consistent with the parameter list and return value type of the abstract method in the functional interface.

1. Replacing Anonymous Inner Classes

The most common occasion for lambda expressions is to replace anonymous inner classes. Implementing the Runnable interface is a classic example of anonymous inner classes. The function of lambda expressions is quite powerful, you can replace the entire anonymous inner class with ()->!

package OSChina.Lambda;

import org.junit.Test;

import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Test1{
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("普通,线程启动");
            }
        };
        runnable.run();
        test2();
        test3();
        test4();
        test5();
    }

    //无参数,无返回值
    public static void test2() {
        //“->”左边只有一个小括号,表示无参数,右边是Lambda体(就相当于实现了匿名内部类里面的方法了,(即就是一个可用的接口实现类了。))
        Runnable runnable = ()->System.out.println("Lambda 表达式方式,线程启动");
        runnable.run();
    }

    //有一个参数,并且无返回值
    public static void test3() {
        //这个e就代表所实现的接口的方法的参数,
        Consumer<String> consumer = e->System.out.println("Lambda 表达式方式,"+e);
        consumer.accept("传入参数");
    }

    //有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
    public static void test4() {
        //Lambda 体中有多条语句,记得要用大括号括起来
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
        int compare = com.compare(100, 244);
        System.out.println("有两个以上的参数,有返回值,"+compare);
    }

    //若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
    public static void test5() {
        //Comparator com = (x, y) -> Integer.compare(100, 244);
        System.out.println("若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写,"+Integer.compare(100, 244));
    }
}

2. Four built-in functional interfaces of Java 8

If you use lambda and you have to write an interface yourself, it is too troublesome, so Java provides some interfaces:

1. Consumer consumer interface: void accept(T t);

    //有一个参数,并且无返回值
    public static void test3() {
        //这个e就代表所实现的接口的方法的参数,
        Consumer<String> consumer = e->System.out.println("Lambda 表达式方式,"+e);
        consumer.accept("传入参数");
    }

2. Supplier supply interface: T get();

package OSChina.Lambda;

import java.util.ArrayList;
import java.util.function.Supplier;

public class Test2 {
    public static void main(String[] args) {
        ArrayList<Integer> res = getNumList(10,()->(int)(Math.random()*100));
        System.out.println(res);
    }

    public static ArrayList<Integer> getNumList(int num, Supplier<Integer> sup){
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer e = sup.get();
            list.add(e);
        }
        return list;
    }
}

3. Function functional interface: R apply(T t);

package OSChina.Lambda;

import java.util.function.Function;

public class Test2 {
    public static void main(String[] args) {
        String newStr = strHandler("abc",(str)->str.toUpperCase());
        System.out.println(newStr);
        newStr = strHandler("  abc  ",(str)->str.trim());
        System.out.println(newStr);
    }

    public static String strHandler(String str, Function<String,String>fun){
        return fun.apply(str);
    }
}

4. Predicate assertion interface: boolean test(T t);

Judge some string arrays to judge the length >2of the string:

package OSChina.Lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Test2 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("hello","jiangshuying","lambda","www","ok","q");
        List<String> ret = filterStr(list,(str)->str.length()>2);
        System.out.println(ret);
    }

    public static List<String> filterStr(List<String> list, Predicate<String> pre){
        ArrayList<String> arrayList = new ArrayList<>();
        for(String str:list){
            if(pre.test(str)) {
                arrayList.add(str);
            }
        }
        return arrayList;
    }
}

3. Method references and constructor references

Requirement: The parameter list and return value type of the abstract method must be consistent with the parameter list and return value type of the method referenced by the method!

Method reference: Use the operator "::" to separate a class from a method.

object::instance method name
class::static method name
class::instance method name

for example:

    public static void test9(){
        Comparator<Integer> comparator = (x,y)->Integer.compare(x,y);
        Comparator<Integer> comparator1 = Integer::compare;
        int compare = comparator.compare(1,2);
        int compare1 = comparator1.compare(1,2);
        System.out.println("compare:"+compare);
        System.out.println("compare1:"+compare1);
    }

Fourth, some common uses of lambda expressions

1. Use lambda expressions to iterate over collections

package OSChina.Lambda;

import java.util.Arrays;
import java.util.List;

public class Test3 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("java","c#","javascript");
        //before java8
        for (String str:list){
            System.out.println("before java8,"+str);
        }
        //after java8
        list.forEach(x-> System.out.println("after java8,"+x));
    }
}

2. Implement map with lambda expressions

The map function is arguably the most important method in functional programming. The role of map is to transform one object into another . In our case, the cost is increased by a factor of 0,05 through the map method and then output.

package OSChina.Lambda;

import java.util.Arrays;
import java.util.List;

public class Test3 {
    public static void main(String[] args) {
        List<Double> list = Arrays.asList(10.0,20.0,30.0);
        list.stream().map(x->x+x*0.05).forEach(x-> System.out.println(x));
    }
}

3. Use lambda expressions to implement map and reduce

Since map is mentioned, how can we not mention reduce. Like map, reduce is one of the most important methods in functional programming. . . The role of map is to change one object into another, while reduce realizes the combination of all values ​​into one , see:

package OSChina.Lambda;

import java.util.Arrays;
import java.util.List;

public class Test3 {
    public static void main(String[] args) {
        //before java8
        List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
        double sum = 0;
        for(double each:cost) {
            each += each * 0.05;
            sum += each;
        }
        System.out.println("before java8,"+sum);
        //after java8
        List<Double> list = Arrays.asList(10.0,20.0,30.0);
        double sum2 = list.stream().map(x->x+x*0.05).reduce((sum1,x)->sum1+x).get();
        System.out.println("after java8,"+sum2);
    }
}

I believe that the writing method of map+reduce+lambda expression is more than one level higher.

4, filter operation

Filter is also an operation we often use. When manipulating collections, it is often necessary to filter out some elements from the original collection.

package OSChina.Lambda;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Test3 {
    public static void main(String[] args) {
        List<Double> cost = Arrays.asList(10.0, 20.0,30.0,40.0);
        List<Double> filteredCost = cost.stream().filter(x -> x > 25.0).collect(Collectors.toList());
        filteredCost.forEach(x -> System.out.println(x));
    }
}

5. Cooperate with functional interface Predicate

In addition to supporting the functional programming style at the language level, Java 8 also added a package called java.util.function. It contains many classes to support functional programming in Java. One of them is Predicate. Using the java.util.function.Predicate functional interface and lambda expressions, you can add logic to API methods to support more dynamic behaviors with less code. The Predicate interface is very useful for filtering.

package OSChina.Lambda;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Test4 {
    public static void filterTest(List<String> languages, Predicate<String> condition) {
        languages.stream().filter(x -> condition.test(x)).forEach(x -> System.out.println(x + " "));
    }

    public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java","Python","scala","Shell","R");
        filterTest(languages,x->x.startsWith("J"));//Java 
        filterTest(languages,x -> x.endsWith("a"));//Java,scala 
        filterTest(languages,x -> true);//Java,Python,scala,Shell,R
        filterTest(languages,x -> false);//
        filterTest(languages,x -> x.length() > 4);//Python,scala,Shell,
    }
}

 

This blogger has entered CSDN in an all-round way, I hope everyone will support me, thank you very much!

[CSDN] [Java8 new features] Lambda expression summary (full stack strongest, absolutely arrogant)

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324129354&siteId=291194637