JDK8新特性2 (续)

导读:本篇文章讲解 JDK8新特性2 (续),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

方法引用

在这里插入图片描述

方法引用—代码:

Emp :

package com.test4;

public class Emp {
    private String name;
    private String sex;
    private Integer age;

    public Emp() {
    }

    public Emp(String name, String sex, Integer age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}

Test1 :

package com.test4;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class Test1 {
    public static void main(String[] args) {
        //普通的lambda
//        Consumer<String> consumer = (s)->{
//            //System.out.println(s);
//            //获取打印流对象
//            PrintStream out = System.out;
//            //调用打印流的打印方法
//            out.println(s);
//        };


        //1.实例对象方法引用:简化lambda写法
        //Consumer<String> consumer = System.out::println;
        //打印传入数据
        //consumer.accept("张三");
        //consumer.accept("李四");

        //两个数的比较
//        int compare = Integer.compare(10, 10);
//        System.out.println(compare);
        //Comparator<Integer> comparator = (n1,n2)->Integer.compare(n1,n2);

        //2.类的静态方法引用
//        Comparator<Integer> comparator = Integer::compare;
//        System.out.println( comparator.compare(10,5));
//        System.out.println( comparator.compare(10,20));
//        System.out.println( comparator.compare(10,10));

        //3.类的实例方法的方法引用
        //Function<Emp,String> function = (e)->e.getName();
//        Function<Emp,String> function = Emp::getName;
//        Emp emp = new Emp();
//        emp.setName("李四");
//        emp.setSex("男");
//        emp.setAge(20);
//        String s = function.apply(emp);
//        System.out.println(s);

        //4.类的构造方法引用
        //Supplier<Emp> supplier = ()->new Emp();
        Supplier<Emp> supplier = Emp::new;
        Emp emp = supplier.get();
        System.out.println(emp);
    }
}

布局&运行结果:

在这里插入图片描述

Stream流

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

获取stream对象的方式—代码:

Test1 :

package com.test5;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test1 {
    public static void main(String[] args) {
        //Stream流的使用
        List<String> list = new ArrayList<>();
        list.add("bbb");
        list.add("ccc");
        list.add("aaa");
        list.add("ddd");
        list.add("111");
        list.add("333");
        //通过集合获取流对象:串行流
        Stream<String> stream = list.stream();
        stream.forEach(System.out::println);
        System.out.println("==================");
        //获取并行流
        Stream<String> stream2 = list.parallelStream();
        //定义要做的处理
        //Consumer<String> consumer = s -> System.out.println(s);
        //Consumer<String> consumer=System.out::println;
        //通过流对象执行处理
        stream2.forEach(System.out::println);

        //将数组转为流
        String[] strs= {"aaa","bbb","ccc"};
        //通过Arrays将数组转为流,进行遍历
        //Arrays.stream(strs).forEach(System.out::println);

        //使用Stream.of创建流对象
        Stream<Integer> mystream = Stream.of(100, 200, 300);
        //mystream.forEach(System.out::println);

        //一元运算接口对象:传入一个类型的数据,返回一个同类型的结果
        UnaryOperator<Integer> unaryOperator = n->n+5;
        //System.out.println(unaryOperator.apply(10));
        //System.out.println(unaryOperator.apply(20));
        //System.out.println(unaryOperator.apply(30));

        //使用Stream的迭代操作 iterator
        //以0为基础,做+5操作,做10次,输出结果
        //Stream.iterate(0,unaryOperator).limit(10).forEach(System.out::println);

        //使用Stream的generator方法,生成任意个数据
        Supplier<Integer> supplier = ()->new Random().nextInt(50);
        //使用流生成20个1-50的随机数
        //Stream.generate(supplier).limit(20).forEach(System.out::println);

        //针对特定类型数据的Stream对象,生成指定类型的区间数字(0-100)
        IntStream intStream = IntStream.rangeClosed(0,100);
        //intStream.forEach(System.out::println);


    }
}

在这里插入图片描述

中间操作—代码:

Emp :

package com.test6;

import java.util.Objects;

public class Emp {
    private String name;
    private String sex;
    private Integer age;
    private Integer salary;

    public Emp(){}

    public Emp(String name, String sex, Integer age, Integer salary) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Emp emp = (Emp) o;
        return Objects.equals(name, emp.name) && Objects.equals(sex, emp.sex) && Objects.equals(age, emp.age) && Objects.equals(salary, emp.salary);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, sex, age, salary);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

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

    public Integer getSalary() {
        return salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

Test :

package com.test6;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {
        List<Emp> list = new ArrayList<>();
        list.add(new Emp("小红","女",20,18000));
        list.add(new Emp("小刚","男",18,28000));
        list.add(new Emp("小绿","男",19,8000));
        list.add(new Emp("小白","女",17,12000));
        list.add(new Emp("小刚","男",18,28000));
        list.add(new Emp("小微","女",15,10000));
        list.add(new Emp("小超","男",25,100000));
        list.add(new Emp("小明","男",21,1000));
        list.add(new Emp("小超","男",25,100000));
        //过滤员工薪资大于10000的
        //Predicate<Emp> predicate = e->e.getSalary()>10000;
        //filter:过滤
        //list.stream().filter(e->e.getSalary()>10000).forEach(System.out::println);

        //limit取前几条
        //list.stream().limit(3).forEach(System.out::println);

        //skip跳过几条
        //list.stream().skip(3).forEach(System.out::println);

        //distinct去重:对对象重写equals和hashcode方法
        //list.stream().distinct().forEach(System.out::println);

        //sorted:排序
        //定义比较器,比较两个员工的薪资
        //Comparator<Emp> comparator = (e1,e2)->e1.getSalary()-e2.getSalary();
//        list.stream().sorted((e1,e2)->e1.getSalary()-e2.getSalary())
//                     .forEach(System.out::println);

        //map映射:Funtion进行数据处理,传入一个数据返回一个结果
        //将所有员工(对象)的姓名(属性)返回输出
        //Function<Emp,String> function = Emp::getName;
        //list.stream().map(Emp::getName).forEach(System.out::println);
        //先去重,再映射(获取属性),再输出
        list.stream().distinct().map(Emp::getName).forEach(System.out::println);

        //自己练习:去重之后,将薪资大于10000,男生,姓张的,姓名,取前两个,打印处理
        list.stream().filter(emp -> emp.getSalary()>10000 && emp.getSex().equals("男") && emp.getName().contains("小")).map(Emp::getName).limit(2).forEach(System.out::println);
    }
}

布局&运行结果:

在这里插入图片描述

串行流和并行流的比较—代码:

Test1 :

package com.test7;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Test1 {
    public static void main(String[] args) {
        //测试串行流和并行流的时间消耗
        List<String> list = new ArrayList<>();
        for (int i=0;i<50000;i++){
            list.add(UUID.randomUUID().toString());
        }

        //记录开始时间
        long start = System.currentTimeMillis();
        //串行流:将数据排序,并统计数量
        //list.stream().sorted().count();
        //并行流:数据排序,并统计数量
        list.parallelStream().sorted().count();
        long end = System.currentTimeMillis();
        System.out.println("花费的时间:"+(end-start));
    }
}

布局&运行结果:

在这里插入图片描述

终止操作—代码:

Emp :

package com.test8;

import java.util.Objects;

public class Emp {
    private String name;
    private String sex;
    private Integer age;
    private Integer salary;

    public Emp(){}

    public Emp(String name, String sex, Integer age, Integer salary) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Emp emp = (Emp) o;
        return Objects.equals(name, emp.name) && Objects.equals(sex, emp.sex) && Objects.equals(age, emp.age) && Objects.equals(salary, emp.salary);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, sex, age, salary);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

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

    public Integer getSalary() {
        return salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

Test1 :

package com.test8;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class Test1 {
    public static void main(String[] args) {
        //流的结果(终止)操作
        //foreach,min,max,count
        List<Emp> list = new ArrayList<>();
        list.add(new Emp("小红","女",20,18000));
        list.add(new Emp("小刚","男",18,28000));
        list.add(new Emp("小绿","男",19,8000));
        list.add(new Emp("小白","女",17,12000));
        //list.add(new Emp("小刚","男",18,28000));
        list.add(new Emp("小微","女",15,10000));
        list.add(new Emp("小超","男",25,100000));
        list.add(new Emp("小明","男",21,1000));
        //list.add(new Emp("小超","男",25,100000));

        //求薪资最低的数据
        Optional<Emp> min = list.stream().min((e1, e2) ->e1.getSalary()-e2.getSalary());
        //获取最小薪资的员工
        //System.out.println(min.get());

        //求年龄最大的员工
        Optional<Emp> max = list.stream().max((e1, e2) -> e1.getAge() - e2.getAge());
        //System.out.println(max.get());

        //count:求薪资大于10000的男生数量
        long count = list.stream().filter(e -> e.getSalary() > 10000) //过滤薪资大于10000
                    .filter(e -> e.getSex().equals("男")) //过滤男生
                    .count();
        //System.out.println("数量:"+count);

        //reduce:做数据合并
        BinaryOperator<Integer> binaryOperator =(s1,s2)->s1+s2;
        //将所有人的薪水加到一起
        //Optional<Integer> reduce = list.stream().map(Emp::getSalary).reduce(binaryOperator);
        //System.out.println("所有人的薪水和:"+reduce.get());

        //Collect:数据打包,把数据存储到集合中
        //将所有薪水大于10000的数据,存储List中
        List<Emp> collect = list.stream().filter(e -> e.getSalary() > 10000).collect(Collectors.toList());
        //System.out.println(collect);
        collect.stream().forEach(System.out::println);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118022.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!