ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

lambda表达式Stream流使用

2019-08-30 11:07:14  阅读:210  来源: 互联网

标签:Apple Stream List System println new out 表达式 lambda


#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());
    }
}

标签:Apple,Stream,List,System,println,new,out,表达式,lambda
来源: https://blog.csdn.net/mxlgslcd/article/details/100152365

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有