Java8-functionInterface

admin
2022-09-06 / 0 评论 / 170 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年09月08日,已超过808天没有更新,若内容或图片失效,请留言反馈。

Lambda表达式用法

用户范例
package com.example.study.java8.InterfaceFunction;

/**
 * lambda表达式用法
 */
public class LambdaUsage {
    public static void main(String[] args) {
        Runnable runnable1 = ()-> System.out.println("hello");

        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        };

        process(runnable1);
        process(runnable2);
        process(()-> System.out.println("hello"));
    }

    public static void process(Runnable runnable){
        runnable.run();
    }
}

学习目标

一、Predicate:诊断,返回boolean类型

@FunctionalInterface
public interface Predicate {

/**  
 * Evaluates this predicate on the given argument.     *     * @param t the input argument  
 * @return {@code true} if the input argument matches the predicate,  
 * otherwise {@code false}  
 */  
boolean test(T t);

二、Consumer:消费者,没有返回类型

@FunctionalInterface
public interface Consumer {

/**  
 * Performs this operation on the given argument.     *     * @param t the input argument  
 */    void accept(T t);

三、Function:函数有返回值

@FunctionalInterface
public interface Function<T, R> {

/**  
 * Applies this function to the given argument.     *     * @param t the function argument  
 * @return the function result  
 */    R apply(T t);

四、Supplier:生成者:返回一个对象

@FunctionalInterface
public interface Supplier {

/**  
 * Gets a result.     *     * @return a result  
 */    T get();

详细说明

1、Predicate详细用法

范例:


package com.example.study.java8.InterfaceFunction;

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

/**
 * Lambda表达式的使用:Prodicate用法
 */
public class LambdaUsagePredicate {
    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("red", 10)
                , new Apple("red", 60)
                , new Apple("blue", 40)
                , new Apple("black", 30)
                , new Apple("green", 80)
                , new Apple("blue", 90)
                , new Apple("green", 60)
                , new Apple("green", 50)
                , new Apple("red", 20));

        //Predicate用法
        List<Apple> filterList = filter(list, apple -> apple.getColor().equals("green"));

        for (Apple apple : filterList) {
            System.out.println(apple.toString());
        }

        System.out.println("============================");


        //其它类似Predicate用法
        //IntegerPredicate用法
        List<Apple> filterByWeight = predicateByWeight(list, weight -> weight == 60);
        for (Apple apple : filterByWeight) {
            System.out.println(apple.toString());
        }


        System.out.println("============================");

        //BiPredicate用法
        List<Apple> biPredicateResult = biPredicateByColorAndWeight(list, (color, weight) -> {
            return color.equals("green") && weight == 60;
        });
        for (Apple apple : biPredicateResult) {
            System.out.println(apple.toString());
        }
    }


    //1、Predicate:诊断的用法
    public static List<Apple> filter(List<Apple> sources, Predicate<Apple> predicate) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : sources) {
            if (predicate.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }


    //2、其它类似Predicate用法
    //IntegerPredicate用法
    public static List<Apple> predicateByWeight(List<Apple> source, IntPredicate intPredicate) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            if (intPredicate.test(apple.getWeight())) {
                result.add(apple);
            }
        }
        return result;
    }

    //3、带2个参数的BiPredicate用法
    public static List<Apple> biPredicateByColorAndWeight(List<Apple> source, BiPredicate<String, Integer> biPredicate) {
        List<Apple> result = new ArrayList<Apple>();
        for (Apple apple : source) {
            if (biPredicate.test(apple.getColor(), apple.getWeight())) {
                result.add(apple);
            }
        }
        return result;
    }
}

2、Consumer详细用法

范例:


package com.example.study.java8.InterfaceFunction;

import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * Lambda表达式:Consumer用法
 */
public class LambdaUasgeConsumer {
    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("red", 10)
                , new Apple("red", 60)
                , new Apple("blue", 40)
                , new Apple("black", 30)
                , new Apple("green", 80)
                , new Apple("blue", 90)
                , new Apple("green", 60)
                , new Apple("green", 50)
                , new Apple("red", 20));


        //1个参数调用
        simpleUsageConsumer(list, apple -> System.out.println(apple.toString()));

        System.out.println("========================");
        twoArgsUsageConsumer("我买了水果",list, (apple, name)->{
            System.out.println(name+",颜色:"+apple.getColor()+"\t 重量:"+apple.getWeight());
        });
    }

    //1、一个参数用法
    public static void simpleUsageConsumer(List<Apple> source, Consumer<Apple> consumer) {
        for (Apple apple : source) {
            consumer.accept(apple);
        }
    }

    //2、两个参数用法
    public static void twoArgsUsageConsumer(String name, List<Apple> source, BiConsumer<Apple, String> consumer) {
        for (Apple apple : source) {
            consumer.accept(apple, name);
        }
    }
}

3、Funcation详细用法

范例:

package com.example.study.java8.InterfaceFunction;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntFunction;

/**
 * Lambda表达式:Funcation用法
 */
public class LambdaUsageFuncation {
    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("red", 10)
                , new Apple("red", 60)
                , new Apple("blue", 40)
                , new Apple("black", 30)
                , new Apple("green", 80)
                , new Apple("blue", 90)
                , new Apple("green", 60)
                , new Apple("green", 50)
                , new Apple("red", 20));

        //1、2个参数调用
        List<String> stringsUsageFuncation = simpleUsageFuncation(list, apple -> apple.getColor() + ":颜色");
        for(String color: stringsUsageFuncation){
            System.out.println(color);
        }

        System.out.println("============================");

        //2、其它用法IntFuncation调用
        List<Integer> integerList = intUsageFuncation(list, weight-> weight*20);
        for(Integer i : integerList){
            System.out.println(i);
        }

        System.out.println("==============================");
        //3、3个参数调用
        Apple newApple = threeeUsageFuncation("彩色", 178, (newColor, newInteger) -> {
            return  new Apple(newColor, newInteger);
        });
        System.out.println(newApple.toString());
    }

    //1、2个参数 简单用法
    public static List<String> simpleUsageFuncation(List<Apple> source, Function<Apple, String> function){
        List<String > result = new ArrayList<>();
        for(Apple apple:source){
            result.add(function.apply(apple));
        }
        return result;
    }

    //2、其它用法IntFuncation
    public static List<Integer> intUsageFuncation(List<Apple> source, IntFunction<Integer> function){
        List<Integer > result = new ArrayList<>();
        for(Apple apple:source){
            result.add(function.apply(apple.getWeight()));
        }
        return result;
    }

    //3、3个参数用法
    public static  Apple threeeUsageFuncation(String newColor, Integer newWeight, BiFunction<String, Integer, Apple> biFunction){
        return biFunction.apply(newColor, newWeight);
    }

}

4、Supplier详细用户

范例:

package com.example.study.java8.InterfaceFunction;

import java.util.function.Supplier;

/**
 * Lamdba表达式之Supplier用法
 */
public class LambdaUsageSupplier {
    public static void main(String[] args) {

        //范例1
        Supplier<String> stringSuppier = String::new;
        System.out.println(stringSuppier.get().getClass());

        System.out.println("=====================");

        //范例2
        Apple apple = createApple(() -> {
            return new Apple("五颜六色", 200);
        });
        System.out.println(apple.toString());
    }

    public static Apple createApple(Supplier<Apple> supplier){
        return supplier.get();
    }
}

注意:参数类型

package com.example.study.java8.InterfaceFunction;

/**
 * 参数类型注意
 */
public class ArgsCase {
    public static void main(String[] args) {
        int i =0;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //i会报错提示:
                //Variable 'i' is accessed from within inner class, needs to be final or effectively final
//                i++;
            }
        };
        i++;

        //Lambda表达式
        Runnable runnable1 = ()->{
            //i同样报错提示:
            //Variable used in lambda expression should be final or effectively final
//            System.out.println(i);
        };
        i++;
    }
}
5

评论 (0)

取消