JDK8新特性lambda与stream

Java8新特性

开始之前先建立一个maven项目
在这里插入图片描述
在这里插入图片描述

接口中默认方法修饰为普通方法

在jdk8之前,interface之中可以定义变量何方法,变量必须是public、static、final的,方法必须是public、abstract的,由于这些修饰符都说默认的。

接口定义方法:public抽象方法需要子类实现
接口定义变量:public、static、final

在JDK1.8开始支持使用static何default修饰可以写方法体,不需要子类重写。
方法:
普通方法 可以有方法体
抽象方法 没有方法体需要子类实现重写。

代码案例
创建一个JDK8Interface接口,包名:com.wdp.java8

package com.wdp.java8;

public interface JDK8Interface {

    void addOrder();

    default void getDefaultOrder(){
        System.out.println("我是默认方法体");
    }

    static void getStaticOrder(){
        System.out.println("我是静态方法体");
    }
}

创建一个JDK8InterfaceImpl类并且实现JDK8Interface接口,
包名:com.wdp.java8

package com.wdp.java8;

public class JDK8InterfaceImpl implements JDK8Interface {

    /**
     * 默认的情况下必须重写接口中抽象方法 默认方法和静态方法是不需要必须重写
     */

    @Override
    public void addOrder() {
        System.out.println("addOrder");
    }
}

创建一个Test01来做测试,包名:com.wdp.java8

package com.wdp.java8;

public class Test01 {
    public static void main(String[] args) {
        JDK8InterfaceImpl jdk8Interface = new JDK8InterfaceImpl();
        jdk8Interface.addOrder();
        jdk8Interface.getDefaultOrder();
        //静态方法要直接使用接口调用
        JDK8Interface.getStaticOrder();
    }
}

运行结果:
在这里插入图片描述

Lambda表达式

什么是Lambda表达式
Lambda好处:简化我们匿名内部类的调用。
Lambda+方法引入 代码变得更加精简。
Lambda表达式 (lambda expression) 是一个匿名函数,简化我们调用匿名函数的过程。
百度百科介绍:
https://baike.baidu.com/item/Lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F/4585794?fr=aladdin

为什么要使用Lambda表达式

可以非常简洁的形式调用我们的匿名函数接口。
创建一个Test02类,包名:com.wdp.java8

package com.wdp.java8;

public class Test02 {
    public static void main(String[] args) {
        // 1、使用new的实现类的形式调用接口
        JDK8Interface jdk8Interface = new JDK8InterfaceImpl();
        jdk8Interface.addOrder();

        //2、使用匿名内部类调用
        JDK8Interface jdk8Interface1 = new JDK8Interface() {
            @Override
            public void addOrder() {
                System.out.println("get");
            }
        };
        jdk8Interface1.addOrder();

        //3、使用Lambda调用接口
        ((JDK8Interface)() -> System.out.println("使用lambda调用接口")).addOrder();
        //4、lambuda创建线程
        new Thread(() -> System.out.println(Thread.currentThread().getName()+",run")).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个线程");
            }
        }).start();


    }
}

Lambda表达式的规范

使用Lambda表达式 依赖于函数接口
1、在接口中只能够允许有一个抽象方法
2、在函数接口中定义object类中方法
3、使用默认或者静态方法
4、@FunctionalInterface 表示该接口为函数接口

Java中使用Lambda表达式的规范,必须是为函数接口
函数接口的定义:在该接口中只能存在一个抽象方法,该接口背作为函数接口

JDK中自带的函数接口:
java.lang.Runnable
java.util.concurrent.Callable
java.security.PrivilegedAction
java.util.Comparator
java.io.FileFilter
java.nio.file.PathMatcher
java.lang.reflect.InvocationHandler
java.beans.PropertyChangeListener
java.awt.event.ActionListener
javax.swing.event.ChangeListener

我们也可以使用@FunctionalInterface修饰为函数接口

函数接口定义

1、在接口中只能有一个抽象方法
2、@FunctionalInterface 标记为该接口为函数接口
3、可以通过default修饰为普通方法
4、可以定义object类中的方法

Java系统内置那些函数接口

消费型接口:
Conusmer
void accept(T t);
BiConusmer<T,U>
void accept(T t,U u);//增加一种入参类型

供给型接口
Supplier
void get();

函数型接口
Function<T ,R>
R apply(T t);
UnaryOperator
T apply(T t);//入参与返回值类型一致
BiFunction <T ,U,R>
R apply(T t,U u);//增加一个参数类型
BinaryOperator
T apply(T t1,T t2);//l两个相同类型入参与同类型返回值
ToIntFunction//限定返回int
ToLongFunction//限定返回long
ToDoubleFunction//限定返回double
IntFunction//限定入参int,返回泛型R
LongFunction//限定入参long,返回泛型R
DoubleFunction//限定入参double,返回泛型R

断言型接口
Predicate
boolean test(T t);

Lambda基础语法

() —参数列表
-> 分割
{} 方法体
(a,b)->{
}
无参方法调用
带参数方法调用

(函数接口的参数列表 不需要写类型 需要定义参数名称)->{方法体}

():函数方法参数列表
->分隔 {}方法体
(a,b)->{
Sout(a,b)
}

():函数方法参数列表
->分割{}方法体
(a,b)->{
Sout(a,b)
}

Lambda语法:
()->参数列表
->分割
{}:方法体
()->{}

无参方法调用
创建一个AcanthopanaxInterface接口,包名:com.wdp.java8.service

package com.wdp.java8.service;

@FunctionalInterface
public interface AcanthopanaxInterface {

    void get();
}

创建一个Test03类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.service.AcanthopanaxInterface;

public class Test03 {
    public static void main(String[] args) {

        //使用匿名内部类调用
        new AcanthopanaxInterface() {
            @Override
            public void get() {
                System.out.println("get");
            }
        }.get();
        //使用lambda表达式调用
        AcanthopanaxInterface acanthopanaxInterface = () -> System.out.println("使用lambda表达式调用");
        acanthopanaxInterface.get();
    }
}

运行结果:
在这里插入图片描述
带参数和返回值
创建一个YouShenInterface接口,包名:com.wdp.java8.service

package com.wdp.java8.service;

@FunctionalInterface
public interface YouShenInterface {
    String get(int i, int j);
}

创建一个Test04类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.service.YouShenInterface;

public class Test04 {
    public static void main(String[] args) {
        //1、使用匿名内部类调用
        YouShenInterface youShenInterface = new YouShenInterface() {
            @Override
            public String get(int i, int j) {
                return i + "-" + j;
            }
        };
        System.out.println(youShenInterface.get(1,20));

        //2、使用lambda方式调用有参函数方法
        YouShenInterface youShenInterface1 = (i,j) -> {
            return i+"-"+j;
        };
        System.out.println(youShenInterface1.get(1,30));
    }
}

精简语法
创建一个Test05类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.service.AcanthopanaxInterface;
import com.wdp.java8.service.YouShenInterface;

public class Test05 {
    public static void main(String[] args) {
        AcanthopanaxInterface acanthopanaxInterface = () -> {
            System.out.println("我是方法");
        };
        acanthopanaxInterface.get();
        //精简改为: 如果方法体中只有一条语句的情况下 可以不需要写{}
        AcanthopanaxInterface acanthopanaxInterface1 = () -> System.out.println("我是精简方法1");
        acanthopanaxInterface1.get();
        //3、如果方法体只有一条return的情况下不需要写{}和return
        YouShenInterface youShenInterface = (i,j) -> i+"-"+j;
        System.out.println(youShenInterface.get(1,3));
        String s = ((YouShenInterface) (i, j) -> i + "-" + j).get(1, 4);
        System.out.println(s);
    }
}

方法引入

什么是方法引入
方法引入:需要结合lambda表达式能够让代码变得更加精简。
1、匿名内部类使用
2、Lambda调用匿名内部类
3、方法引入
方法引入
1、静态方法引入:类名:: (静态) 方法名称
2、对象方法引入:类名:: 实例方法名称
3、实例方法引入:new对象 对象实例::方法引入
4、构造函数引入:类名::new


需要遵循一个规范:
方法引入 方法参数列表、返回类型与函数接口参数列表与返回类型必须
要保持一致。

Lambda: 匿名内部类使用代码简洁问题。

在这里插入图片描述

方法引用提供了非常有用的语法,可以直接引用已有的java类或对象的方法或构造器。方法引用其实也离不开Lambda表达式,与lambda联合使用,方法引用可以使语言的构造更加紧凑简洁,减少冗余代码。

方法引用提供非常有用的语法,可以直接引用已有的java类或者对象中方法或者构造函数,方法引用需要配合Lambda表达式语法一起使用减少代码的冗余性问题。

构造器引入
静态方法引入
对象方法引入
实例方法引入

方法引入规则

方法引入实际上就是lambda表达式中直接引入的方法。

必须遵循规范:引入的方法参数列表返回类型必须要和函数接口参数列表、返回类型保持一致。

静态方法引入
创建一个MessageInterface接口,包名:com.wdp.java8.service

package com.wdp.java8.service;

@FunctionalInterface
public interface MessageInterface {
    void get(Integer a);
}

创建一个Test06类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.service.MessageInterface;

public class Test06 {
    public static void main(String[] args) {
        //1、使用匿名内部类调用
        MessageInterface messageInterface = new MessageInterface() {
            @Override
            public void get(Integer a) {
                System.out.println("geta:" + a);
            }
        };
        messageInterface.get(1);

        // 在Lambda表达式中方法体直接引入方法
        MessageInterface messageInterface2 = (a) -> Test06.staticGet(a);
        //方法引入 --实际上就是我们 Lambda表达式中方法体直接引入方法---
        messageInterface2.get(2);

        //方法引入写法
        MessageInterface messageInterface3 = Test06::staticGet;
        messageInterface3.get(3);

    }

    public static String  staticGet(Integer a) {
        System.out.println("staticGet,a:" + a);
        return "123456";
    }


}

运行结果:
在这里插入图片描述
对象方法引入
创建一个MayiktService接口,包名:com.wdp.java8.service

package com.wdp.java8.service;

import com.wdp.java8.Test07;

public interface MayiktService {
    String get(Test07 test07);

}

创建一个Test07类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.service.MayiktService;

import java.util.function.Function;

public class Test07 {
    public static void main(String[] args) {
        //1、使用匿名内部类形式
        MayiktService mayiktService = new MayiktService() {
            @Override
            public String get(Test07 test07) {
                return test07.objGet();
            }
        };
        System.out.println(mayiktService.get(new Test07()));

        //2、Lambda表达式调用
        MayiktService mayiktService1 = (test07) -> test07.objGet();
        System.out.println(mayiktService1.get(new Test07()));

        // 3.方法引入 在这时候我们函数接口 第一个参数传递test07 返回调用test07.objGet方法
        MayiktService mayiktService2 = Test07::objGet;
        System.out.println(mayiktService2.get(new Test07()));
        //Test7::objGet;----- (test23) -> test7.objGet();


        //   R apply(T t); T  apply方法传递的参数类型 :  R apply 方法返回的类型
        //需要将string类型字符串获取长度
        Function<String,Integer> stringIntegerFunction = (str) -> {
            return str.length();
        };
        Integer abc = stringIntegerFunction.apply("abc");
        System.out.println(abc);

        Function<String,Integer> stringIntegerFunction1 = String::length;
        System.out.println(stringIntegerFunction1.apply("qwert"));

    }

    public String objGet() {
        return "wdp";
    }
}

运行结果:
在这里插入图片描述

实例方法引入
创建一个Test08类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.service.MessageInterface;

public class Test08 {
    public static void main(String[] args) {
        Test08 test08 = new Test08();
        //1、匿名内部类写法
        MessageInterface messageInterface = new MessageInterface() {
            @Override
            public void get(Integer a) {
                test08.get(a);
            }
        };
        messageInterface.get(1);

        MessageInterface messageInterface1 = (a) -> {
            test08.get(a);
        };
        messageInterface1.get(2);

        MessageInterface messageInterface2 = test08::get;
        messageInterface2.get(3);

    }


    public void get(Integer a){
        System.out.println("方法引入get方法:" + a);
    }
}

构造函数引入
创建一个UserEntity类 ,包名:com.wdp.java8.entity

package com.wdp.java8.entity;

public class UserEntity {
    private String userName;
    private int age;

    public UserEntity() {

    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

创建一个UserInterface接口,包名:com.wdp.java8.service

package com.wdp.java8.service;

import com.wdp.java8.entity.UserEntity;

public interface UserInterface {
    UserEntity getUser();
}

创建一个Test09,包名:

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;
import com.wdp.java8.service.UserInterface;

public class Test09 {
    public static void main(String[] args) {
        UserInterface userInterface = () -> new UserEntity();
        System.out.println(userInterface.getUser());
        UserInterface userInterface1 = UserEntity::new;
        System.out.println(userInterface1.getUser());
    }
}

Lambda实战案例

Foreach
创建一个Test10类,包名:com.wdp.java8

package com.wdp.java8;

import java.util.ArrayList;
import java.util.function.Consumer;

public class Test10 {
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("mayikt");
        strings.add("xiaowei");
        strings.add("xiaomin");
        //方式一:
        strings.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println("s:"+s);
            }
        });

        //方式二:
        strings.forEach((o) -> {
            System.out.println(o);
        });
    }
}

Lambda集合排序
创建一个Test11类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.function.Consumer;

public class Test11 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userlists = new ArrayList<>();
        userlists.add(new UserEntity("mayikt", 22));
        userlists.add(new UserEntity("xiaomin", 18));
        userlists.add(new UserEntity("xiaoha", 36));

        userlists.sort(new Comparator<UserEntity>() {
            @Override
            public int compare(UserEntity o1, UserEntity o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        userlists.forEach((o) -> System.out.println(o));

        userlists.sort((o1,o2) -> o1.getAge()-o2.getAge());
        userlists.forEach((Consumer<? super UserEntity>) o-> System.out.println(o));
    }
}

java8 stream流

什么是stream流
Stream是JDK1.8中处理集合的关键抽象概念,Lambda和Stream是JDK1.8新增的函数式编程最有亮点的特性了,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象。Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

这种风格将要处理的元素集合看作一种流,流在管道中传输,并且可以在管道的节点上进行处理,比如筛选,排序,聚合等。

元素流在管道中经过中间操作 (intermediate operation) 的处理,最后由最终操作(terminal operation)得到前面处理的结果。

Stream :非常方便精简的形式遍历集合实现 过滤、排序等。
Mysql:select userName from mayikt where userName =‘mayikt’
Order by age limt(0,2)

在这里插入图片描述
Stream创建方式
parallelStream为并行流采用多线程执行。
Stream采用单线程执行。
parallelStream效率比Stream要高。
创建一个Test12类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;

public class Test12 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
        userEntities.add(new UserEntity("xiaowei", 16));
        userEntities.stream();
        userEntities.parallelStream();
    }
}

Stream将list转换为Set
创建一个Test13类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test13 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
        userEntities.add(new UserEntity("xiaowei", 16));
        //创建Stream流
        Stream<UserEntity> stream = userEntities.stream();
        Set<UserEntity> collect = stream.collect(Collectors.toSet());
        System.out.println(collect);
    }
}

Stream将list转换为Map
创建一个Test14类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test14 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
       // userEntities.add(new UserEntity("xiaowei", 16));
        //创建一个串行流
        Stream<UserEntity> stream = userEntities.stream();
        //key为string类型 value为UserEntity
        Map<String, UserEntity> collect =
                stream.collect(Collectors.toMap(new Function<UserEntity, String>() {
            @Override
            public String apply(UserEntity userEntity) {
                return userEntity.getUserName();
            }
        }, new Function<UserEntity, UserEntity>() {
            @Override
            public UserEntity apply(UserEntity userEntity) {
                return userEntity;
            }
        }));

        //遍历map
        collect.forEach(new BiConsumer<String, UserEntity>() {
            @Override
            public void accept(String s, UserEntity userEntity) {
                System.out.println("s:"+s+ ",:" +userEntity.toString());
            }
        });

    }
}

Stream将Reduce 求和
创建一个Test15类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Stream;

public class Test15 {
    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(10, 30, 80, 60, 10, 70);
        //匿名内部类求和
//        Optional<Integer> reduce = integerStream.reduce(new BinaryOperator<Integer>() {
//            @Override
//            public Integer apply(Integer a1, Integer a2) {
//                return a1 + a2;
//            }
//        });
//        System.out.println(reduce);


        //Lambda表达式求和
        Optional<Integer> reduce1 = integerStream.reduce((a1, a2) -> a1 + a2);
        System.out.println(reduce1.get());


        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
        Stream<UserEntity> stream = userEntities.stream();
        //实体类计算年龄的总和,第一种匿名内部类计算
//        Optional<UserEntity> reduce = stream.reduce(new BinaryOperator<UserEntity>() {
//            @Override
//            public UserEntity apply(UserEntity userEntity, UserEntity userEntity2) {
//                userEntity.setAge(userEntity.getAge() + userEntity2.getAge());
//                return userEntity;
//            }
//        });
//        System.out.println(reduce.get().getAge());

        //实体类计算年龄的总和,第二种用lambda计算
        Optional<UserEntity> reduce = stream.reduce((user1, user2) -> {
            user1.setAge(user1.getAge() + user2.getAge());
            return user1;
        });
        System.out.println(reduce.get().getAge());
    }
}

StreamMax和Min
创建一个Test16类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;

public class Test16 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));

        //创建串行流
        Stream<UserEntity> stream = userEntities.stream();
        //1、匿名内部类求取最大值
//        Optional<UserEntity> max = stream.max(new Comparator<UserEntity>() {
//            @Override
//            public int compare(UserEntity o1, UserEntity o2) {
//                return o1.getAge() - o2.getAge();
//            }
//        });
//        System.out.println(max.get().getAge());
        //2、Lambda表达式求取最大值
//        Optional<UserEntity> max1 = stream.max((o1, o2) -> o1.getAge() - o2.getAge());
//        System.out.println(max1.get().getAge());
        
        //3、Lambda表达式求取最小值
        Optional<UserEntity> min = stream.min((o1, o2) -> o1.getAge() - o2.getAge());
        System.out.println(min.get().getAge());
    }
}

StreamMatch 匹配
anyMatch表示,判断的条件里,任意一个元素成功,返回true
allMatch表示,判断条件里的元素,所有的都是,返回true
noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true

anyMatch
创建一个Test17类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Test17 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        //创建串行流
        Stream<UserEntity> stream = userEntities.stream();
        //1、第一种匿名内部类
//        boolean b = stream.anyMatch(new Predicate<UserEntity>() {
//            @Override
//            public boolean test(UserEntity userEntity) {
//                return "mayikt".equals(userEntity.getUserName());
//            }
//        });
//        System.out.println(b);
        boolean b = stream.anyMatch((user) -> "mayikt".equals(user.getUserName()));
        System.out.println(b);
    }
}

allMatch
创建一个Test18类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Test18 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("liusi", 21));
        userEntities.add(new UserEntity("wangmazi", 19));
        userEntities.add(new UserEntity("xiaoke", 19));
        userEntities.add(new UserEntity("xiaoan", 21));
        Stream<UserEntity> stream = userEntities.stream();
        //1、使用匿名内部类
//        boolean b = stream.allMatch(new Predicate<UserEntity>() {
//            @Override
//            public boolean test(UserEntity userEntity) {
//                return "mayikt".equals(userEntity.getUserName());
//            }
//        });
//        System.out.println(b);

        //2、使用Lambda表达式
        boolean b = stream.allMatch(userEntity -> "mayikt".equals(userEntity.getUserName()));
        System.out.println(b);
    }
}

noneMatch
创建一个Test19类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Test19 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("liusi", 21));
        userEntities.add(new UserEntity("wangmazi", 19));
        userEntities.add(new UserEntity("xiaoke", 19));
        userEntities.add(new UserEntity("xiaoan", 21));
        Stream<UserEntity> stream = userEntities.stream();
        //1、匿名内部类使用
//        boolean b = stream.noneMatch(new Predicate<UserEntity>() {
//            @Override
//            public boolean test(UserEntity userEntity) {
//                return userEntity.getAge() > 35;
//            }
//        });
//        System.out.println(b);

        //2、Lambda表达式使用
        boolean b1 = stream.noneMatch(userEntity -> userEntity.getAge() > 35);
        System.out.println(b1);
    }
}

StreamFor循环
创建一个Test20类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class Test20 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("liusi", 21));
        userEntities.add(new UserEntity("wangmazi", 19));
        userEntities.add(new UserEntity("xiaoke", 19));
        userEntities.add(new UserEntity("xiaoan", 21));
        Stream<UserEntity> stream = userEntities.stream();
        //1、匿名内部类遍历
//        stream.forEach(new Consumer<UserEntity>() {
//            @Override
//            public void accept(UserEntity userEntity) {
//                System.out.println(userEntity.toString());
//            }
//        });

        //2、Lambda表达式遍历
        stream.forEach(userEntity -> {
            System.out.println(userEntity);
        });
    }
}

Stream过滤器
创建一个Test21类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Test21 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("liusi", 21));
        userEntities.add(new UserEntity("wangmazi", 19));
        userEntities.add(new UserEntity("xiaoke", 19));
        userEntities.add(new UserEntity("xiaoan", 21));
        Stream<UserEntity> stream = userEntities.stream();
        //1、匿名内部类过滤
//        stream.filter(new Predicate<UserEntity>() {
//            @Override
//            public boolean test(UserEntity userEntity) {
//                return userEntity.getAge()<=35;
//            }
//        }).filter(new Predicate<UserEntity>() {
//            @Override
//            public boolean test(UserEntity userEntity) {
//                return userEntity.getUserName().equals("zhangsan");
//            }
//        }).forEach(new Consumer<UserEntity>() {
//            @Override
//            public void accept(UserEntity userEntity) {
//                System.out.println(userEntity.toString());
//            }
//        });

        //2、Lambda表达式过滤
        stream.filter(userEntity -> userEntity.getAge()<=35).filter(userEntity -> userEntity.getUserName().equals("zhangsan"))
                .forEach(userEntity -> System.out.println(userEntity));
    }
}

Stream排序 sorted
创建一个Test22类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class Test22 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
        userEntities.add(new UserEntity("mayikt_list", 109));
        userEntities.add(new UserEntity("mayikt_zhangsan", 110));
        userEntities.add(new UserEntity("lisi", 109));
        userEntities.add(new UserEntity("mayikt", 66));
        userEntities.add(new UserEntity("mayikt", 78));
        userEntities.add(new UserEntity("mayikt", 32));
        //创建串行流
        Stream<UserEntity> stream = userEntities.stream();
        //1、匿名内部类实现排序遍历
//        stream.sorted(new Comparator<UserEntity>() {
//            @Override
//            public int compare(UserEntity o1, UserEntity o2) {
//                return o1.getAge()-o2.getAge();
//            }
//        }).forEach(new Consumer<UserEntity>() {
//            @Override
//            public void accept(UserEntity userEntity) {
//                System.out.println(userEntity);
//            }
//        });

        //2、Lambda表达式实现排序遍历
        stream.sorted(((o1, o2) -> o1.getAge()-o2.getAge())).forEach(userEntity -> System.out.println(userEntity));
    }
}

Stream limit和skip
创建一个Test23类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.stream.Stream;

public class Test23 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
        userEntities.add(new UserEntity("mayikt_list", 109));
        userEntities.add(new UserEntity("mayikt_zhangsan", 110));
        userEntities.add(new UserEntity("lisi", 109));
        userEntities.add(new UserEntity("mayikt", 66));
        userEntities.add(new UserEntity("mayikt", 78));
        userEntities.add(new UserEntity("mayikt", 32));
        Stream<UserEntity> stream = userEntities.stream();
        //Limit 从头开始获取 Skip 就是跳过
        stream.skip(2).limit(1).forEach(userEntity -> System.out.println(userEntity));
    }
}

Stream 综合案例
创建一个Test24类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.UserEntity;

import java.util.ArrayList;
import java.util.stream.Stream;

public class Test24 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("mayikt", 20));
        userEntities.add(new UserEntity("meite", 28));
        userEntities.add(new UserEntity("zhangsan", 35));
        userEntities.add(new UserEntity("xiaowei", 16));
        userEntities.add(new UserEntity("mayikt_list", 109));
        userEntities.add(new UserEntity("mayikt_zhangsan", 110));
        userEntities.add(new UserEntity("lisi", 109));
        //要求:对数据流的数据实现降序排列、且名称包含mayikt 获取前两位
        Stream<UserEntity> stream = userEntities.stream();
        stream.sorted((o1, o2) -> o1.getAge()-o2.getAge())
                .filter(userEntity -> userEntity.getUserName().contains("mayikt")).limit(2)
                .forEach(userEntity -> System.out.println(userEntity));
    }
}

并行流与串行流区别

串行流:单线程的方式操作,数据量比较少得时候。
并行流:多线程方式操作,数据量比较大的时候,原理:Fork join将一个大的任务拆分n多个小的子任务并行执行,最后在统计结果,有可能会非常消耗cpu的资源,确实可以提高效率。

注意:数据量比较少的情况下,不要使用并行流。

JDK8Optional

Optional类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
Optional是个容器:它可以保持类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显示进行空值检测。
Optional类的引入很好的解决空指针异常。

判断参数是否为空
ofNullable(可以传递一个空对象)
Of(不可以传递空对象)
代码案例
创建一个Test25类,包名:com.wdp.java8

package com.wdp.java8;

import java.util.Optional;

public class Test25 {
    public static void main(String[] args) {
        //Integer a1 = null;  //为空的情况
        Integer a1 = 1; //不为空的情况
        //ofNullable支持传递null
        Optional<Integer> a11 = Optional.ofNullable(a1);
        System.out.println(a11.isPresent());

        //Integer a2 = null;
        Integer a2 = 1;
        //of传递null会报错的
        Optional<Integer> a21 = Optional.of(a2);
        System.out.println(a21.isPresent());
    }
}

参数为空可以设定默认值
创建一个Test26类,包名:com.wdp.java8

package com.wdp.java8;

import java.util.Optional;

public class Test26 {
    public static void main(String[] args) {
        Integer a3 = 5;
        Optional<Integer> a31 = Optional.ofNullable(a3);
        System.out.println(a31.isPresent()); //判断是否是空
        System.out.println(a31.get()); //获取值

        Integer a4 = null;
        Integer a = Optional.ofNullable(a4).orElse(10);
        System.out.println(a);


    }
}

参数实现过滤
创建一个Test27类,包名:com.wdp.java8

package com.wdp.java8;

import java.util.Optional;

public class Test27 {
    public static void main(String[] args) {
        Integer a1 = 18;
        Optional<Integer> a = Optional.ofNullable(a1);
        boolean present = a.filter(a2 -> a2 > 17).isPresent();
        System.out.println(present);
       
    }
}

与Lambda表达式结合使用,优化代码

优化方案1
创建一个Test28类,包名:com.wdp.java8

package com.wdp.java8;

import java.util.Optional;

public class Test28 {
    public static void main(String[] args) {
        // 优化前
        String mayiktName = null;
        if (mayiktName != null) {
            System.out.println(mayiktName);
        }


        //优化后
        Optional<String> mayiktName1 = Optional.ofNullable(mayiktName);
        //如果为空则不会调用
        //mayiktName1.ifPresent(s -> System.out.print(s));
        mayiktName1.ifPresent(System.out::print);

    }
}

优化方案1
创建一个Test29类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.OrderEntity;

import java.util.Optional;
import java.util.function.Supplier;

public class Test29 {
    private static OrderEntity order = null;


    public static void main(String[] args) {
        OrderEntity order = Test29.getOrder();
        System.out.println(order);
    }

    public static OrderEntity getOrder() {
        //        // 优化前
//        if (order == null) {
//            return createOrder();
//        }
//        return order;

        //优化方案一
//        return Optional.ofNullable(order).orElseGet(new Supplier<OrderEntity>() {
//            @Override
//            public OrderEntity get() {
//                return createOrder();
//            }
//        });

        //优化方案二
       return Optional.ofNullable(order).orElseGet(() -> createOrder());
    }

    private static OrderEntity createOrder() {
        return new OrderEntity("123456", "mayikt");
    }

}

优化方案3
map中获取的返回值自动被Optional包装,即返回值 -> Optional<返回值>

flatMap中返回值保持不变,但必须是Optional类型,即Optional<返回值> ->
Optional<返回值>
创建一个Test30类,包名:com.wdp.java8

package com.wdp.java8;

import com.wdp.java8.entity.OrderEntity;

import java.util.Optional;

public class Test30 {
    public static void main(String[] args) {
        System.out.println(Test30.getOrderName());
    }

    public static String getOrderName() {
        // 优化前写法:
        OrderEntity order = new OrderEntity("123456", "MAyikt");
//        if (order != null) {
//            String orderName = order.getOrderName();
//            if (orderName != null) {
//                return orderName;
//            }
//        }
//
//        return null;
        // 对我们对象中方法 实现处理
        return Optional.ofNullable(order)
                .map(orderEntity -> orderEntity.getOrderName())
                .map(oderName -> oderName.toLowerCase()).orElse("df");
    }



}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值