分享

lambda表达式Stream流使用

 印度阿三17 2019-08-30

#Lambda表达式

Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中)


#lambda表达式本质上就是一个匿名方法。比如下面的例子:

public int add(int x, int y) {
    return x   y;
}

转成Lambda表达式后是这个样子:

(int x, int y) -> x   y;

参数类型也可以省略,Java编译器会根据上下文推断出来:

(x, y) -> x   y; //返回两数之和

或者

(x, y) -> { return x   y; } //显式指明返回值

#java 8 in Action这本书里面的描述:

A lambda expression can be understood as a concise representation of an anonymous function
that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a
return type, and also possibly a list of exceptions that can be thrown. That’s one big definition;

#格式:

(x, y) -> x   y;
-----------------
(x,y):参数列表
x y  : body

#Lambda表达式用法实例:

package LambdaUse;

/**
 * @author zhangwenlong
 * @date 2019/8/25 15:17
 */
public class LambdaUse {

    public static void main(String[] args) {

        //匿名类实现
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello world");
            }
        };
        //Lambda方式实现
        Runnable r2 = ()-> System.out.println("Hello world");

        process(r1);
        process(r2);
        process(()-> System.out.println("Hello world"));
    }
    private  static void  process(Runnable r){
        r.run();
    }
}

输出的结果:

Hello world
Hello world
Hello world

FunctionalInterface注解修饰的函数

#predicate的用法

package LambdaUse;

import java.applet.Applet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.LongPredicate;
import java.util.function.Predicate;

/**
 * @author zhangwenlong
 * @date 2019/8/25 15:30
 */
public class PredicateTest {

    //通过名字(Predicate实现)
    private static List<Apple> filterApple(List<Apple> list, Predicate<Apple> predicate){
            List<Apple> appleList = new ArrayList<>();
            for(Apple apple : list){
                if(predicate.test(apple)){
                    appleList.add(apple);
                }
            }
            return appleList;
    }
    //通过重量(LongPredicate实现)
    private static List<Apple> filterWeight(List<Apple> list, LongPredicate predicate){
        List<Apple> appleList = new ArrayList<>();
        for(Apple apple : list){
            if(predicate.test(apple.getWeight())){
                appleList.add(apple);
            }
        }
        return appleList;
    }

    public static void main(String[] args) {

        List<Apple> list = Arrays.asList(new Apple("苹果",120),new Apple("香蕉",110));
        List<Apple> applelist = filterApple(list,apple -> apple.getName().equals("苹果"));
        System.out.println(applelist);
        List<Apple> appleList = filterWeight(list, (x) -> x > 110);
        System.out.println(appleList);
    }
}


执行结果:

[Apple{name='苹果', weight=120}]
[Apple{name='苹果', weight=120}]

#Lambda表达式的方法推导

package LambdaUse;

import java.util.function.Consumer;

/**
 * @author zhangwenlong
 * @date 2019/8/25 16:02
 */
public class MethodReference {

    private static <T> void useConsumer(Consumer<T> consumer,T t){
        consumer.accept(t);
    }

    public static void main(String[] args) {
        //定义一个匿名类
        Consumer<String> stringConsumer = (s) -> System.out.println(s);
        useConsumer(stringConsumer,"Hello World");
        //lambda
        useConsumer((s) -> System.out.println(s),"ni hao");
        //Lambda的方法推导
        useConsumer(System.out::println,"da jia hao");
    }
}

执行结果:

Hello World
ni hao
da jia hao

参数推导其他例子:

package LambdaUse;

import java.net.Inet4Address;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * @author zhangwenlong
 * @date 2019/8/25 16:53
 */
public class paramterMethod {

    public static void main(String[] args) {
        //情况1:A method reference to a static method (for example, the method parseInt of Integer, written Integer::parseInt)
        //静态方法
        //常用的使用
        Integer value = Integer.parseInt("123");
        System.out.println(value);
        //使用方法推导
        Function<String,Integer> stringIntegerFunction = Integer::parseInt;
        Integer apply = stringIntegerFunction.apply("123");
        System.out.println(apply);
        //情况2:A method reference to an instance method of an arbitrary type (for example, the method length of a String, written String::length)
        //对象的方法
        String ss = "helloWorld";
        System.out.println(ss.charAt(3));
        //推导方法
        BiFunction<String,Integer,Character> stringIntegerCharacterBiFunction = String::charAt;
        System.out.println(stringIntegerCharacterBiFunction.apply(ss,3));

        //情况3:构造函数方法推导
        //常用方式
        Apple apple = new Apple("苹果",120);
        System.out.println(apple);
        //推导方式
        BiFunction<String,Integer,Apple> appleBiFunction = Apple::new;
        System.out.println(appleBiFunction.apply("苹果",120));
    }
}

执行结果:

123
123
l
l
Apple{name='苹果', weight=120}
Apple{name='苹果', weight=120}

具体的详细解释可以参考:

方法推导详解

#Stream(流以及一些常用的方法)
特点:并行处理
例子:

package StreamUse;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangwenlong
 * @date 2019/8/25 17:20
 */
public class StreamTest {

    public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(
                new Apple("苹果",110),
                new Apple("桃子",120),
                new Apple("荔枝",130),
                new Apple("香蕉",140),
                new Apple("火龙果",150),
                new Apple("芒果",160)
        );
        System.out.println(getNamesByCollection(appleList));
        System.out.println(getNamesByStream(appleList));
    }

    //collection实现查询重量小于140的水果的名称
    private static List<String> getNamesByCollection(List<Apple> appleList){
        List<Apple> apples = new ArrayList<>();

        //查询重量小于140的水果
        for(Apple apple : appleList){
            if(apple.getWeight() < 140){
               apples.add(apple);
            }
        }
        //排序
        Collections.sort(apples,(a,b)->Integer.compare(a.getWeight(),b.getWeight()));

        List<String> appleNamesList = new ArrayList<>();
        for(Apple apple : apples){
            appleNamesList.add(apple.getName());
        }
        return  appleNamesList;
    }

    //stream实现查询重量小于140的水果的名称
    private static List<String> getNamesByStream(List<Apple> appleList){
        return  appleList.stream().filter(d ->d.getWeight() < 140)
                .sorted(Comparator.comparing(Apple::getWeight))
                .map(Apple::getName)
                .collect(Collectors.toList());
    }
}

来源:https://www./content-4-425151.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多