Stream流

文章目录

  • 1. 方法引用
  • 2. Stream流
  • 3. 时间日期类
  • 4.练习

1. 方法引用

对象方法引用: 类名::实例方法. (参数1,参数2)->参数1.实例方法(参数2)

package com.zsb.demo06;

import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class Test {
    public static void main(String[] args) {
//        Function<String,Integer> function = (str)->{
//            return str.length();
//        };
        Function<String,Integer> function=String::length;
        Integer len = function.apply("hello");
        System.out.println(len);

        //比较两个字符的内容
//        BiFunction<String,String,Boolean> bi=(t,u)->{
//            return t.equals(u);
//        };
        BiFunction<String,String,Boolean> bi=String::equals;
        Boolean a=bi.apply("hello","world");
        System.out.println(a);

        //
//        Supplier<String> supplier = ()->{
//            return new String("hello");
//        };
        Supplier<People> supplier=People::new;
     //   String s=supplier.get();
        People s=supplier.get();
        System.out.println(s);

    }
}
class People{
    private String name;

    public People() {
    }

    public People(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

2. Stream流

Java8的两个重大改变,一个是Lambda表达式,另一个就是Stream API表达式。Stream 是Java8中处理集合的关键抽象概念,它可以对集合进行非常复杂的查找、过滤、筛选等操作.

2.1为什么使用Stream流

当我们需要对集合中的元素进行操作的时候,除了必需的添加、删除、获取外,最典型的就是集合遍历。我们来体验 集合操作数据的弊端,需求如下:

一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰,何线程
需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据

代码如下:

public class My {
    public static void main(String[] args) {
// 一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰
// 需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");
// 1.拿到所有姓张的
        ArrayList<String> zhangList = new ArrayList<>(); // {"张无忌", "张强", "张三丰"}
        for (String name : list) {
            if (name.startsWith("张")) {
                zhangList.add(name);
            }
        }
// 2.拿到名字长度为3个字的
        ArrayList<String> threeList = new ArrayList<>(); // {"张无忌", "张三丰"}
        for (String name : zhangList) {
            if (name.length() == 3) {
                threeList.add(name);
            }
        }
// 3.打印这些数据
        for (String name : threeList) {
            System.out.println(name);
        }
    }
}

分析:

这段代码中含有三个循环,每一个作用不同:

  1. 首先筛选所有姓张的人;

  2. 然后筛选名字有三个字的人;

  3. 最后进行对结果进行打印输出。

每当我们需要对集合中的元素进行操作的时候,总是需要进行循环、循环、再循环。这是理所当然的么?不是。循环 是做事情的方式,而不是目的。每个需求都要循环一次,还要搞一个新集合来装数据,如果希望再次遍历,只能再使 用另一个循环从头开始。

那Stream能给我们带来怎样更加优雅的写法呢?

Stream的更优写法

package com.zsb.demo07;

import java.util.ArrayList;
import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");

        list.stream()
                .filter(item->item.startsWith("张"))
                .filter(item->item.length()==3)
                .forEach(item-> System.out.println(item));
    }
}

对集合的操作语法简洁:性能比传统快。

2.2 Stream流的原理

注意:Stream和IO流(InputStream/OutputStream)没有任何关系,请暂时忘记对传统IO流的固有印象!

Stream流式思想类似于工厂车间的“生产流水线”,Stream流不是一种数据结构,不保存数据,而是对数据进行加工 处理。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商品。

Stream不存在数据,只对数据进行加工处理。

2.3 如何获取Stream流对象

package com.zsb.demo07;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;

public class Test02 {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        list.add("七七");
        list.add("阿斯托洛吉斯·莫娜·梅姬斯图斯");
        Stream<String> stream = list.stream();

        //通过Arrays数组工具类获取Stream对象
        int[] arr={2,56,89,5,90};
        IntStream stream1 = Arrays.stream(arr);

        //使用Stream类中of方法
        Stream<String> stream2 = Stream.of("hello","world","spring","java");

        //LongStream
        LongStream range = LongStream.range(1,10);
      //  range.forEach(item-> System.out.println(item));

        //上面都是获取的串行流。还可以获取并行流。如果流中的数据量足够大,并行流可以加快处速度。
        Stream<String> stringStream = list.parallelStream();
       // stringStream.forEach(item-> System.out.println(item));
        stringStream.forEach(System.out::println);
    }
}

 

2.4 Stream流中常见的api

中间操作api: 一个操作的中间链,对数据源的数据进行操作。而这种操作的返回类型还是一个Stream对象。

终止操作api: 一个终止操作,执行中间操作链,并产生结果,返回类型不在是Stream流对象。

(1)filter / foreach / count

(2)map | sorted

map--接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素

(3)min max

(4)规约reduce

(5)collect搜集 match find

package com.zsb.demo08;

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

public class Test {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("欧阳雪",18,"中国",'F'));
        personList.add(new Person("Tom",24,"美国",'M'));
        personList.add(new Person("Harley",22,"英国",'F'));
        personList.add(new Person("向天笑",20,"中国",'M'));
        personList.add(new Person("李康",22,"中国",'M'));
        personList.add(new Person("小梅",20,"中国",'F'));
        personList.add(new Person("何雪",21,"中国",'F'));
        personList.add(new Person("李康",22,"中国",'M'));

        //搜集方法collect它属于终止方法
//        // 年龄大于20且性别为M
//        List<Person> collect = personList.stream()
//                .filter(item -> item.getAge() > 20)
//                .filter(item -> item.getSex() == 'M')
//                .collect(Collectors.toList());
//        System.out.println(collect);
        //
//        Optional<Person> any = personList.parallelStream()
//                .filter(item -> item.getSex() == 'F').findAny();
//        System.out.println(any.get());

//        boolean b = personList.parallelStream()
//                .filter(item -> item.getSex() == 'F')
//                .allMatch(item -> item.getAge() >= 20);
//        boolean b = personList.parallelStream()
//                .filter(item -> item.getSex() == 'F')
//                .anyMatch(item -> item.getAge() >= 20);
        boolean b = personList.parallelStream()
                .filter(item -> item.getSex() == 'F')
                .noneMatch(item -> item.getAge() >= 20);
        System.out.println(b);

        //
//        Optional<Person> max1 = personList.stream()
//                .max((o1, o2) -> o1.getName().length() - o2.getName().length());
//        System.out.println(max1.get());


        //查找最大年龄的人. max终止操作
//        Optional<Person> max = personList.stream().max((o1, o2) -> o1.getAge() - o2.getAge());
//        System.out.println(max.get());
        //求集合中所有人的年龄和。
//        Optional<Integer> reduce = personList.stream()
//                .map(item -> item.getAge())
//                .reduce((a, b) -> a + b);
//        System.out.println(reduce.get());

        //集合中每个元素只要名.map--->原来流中每个元素转换为另一种格式。
//        personList.stream()
//                .map(item->item.getName())
//                .forEach(System.out::println);
//
//        personList.stream()
//                .map(item->{
//                    Map<String,Object> m =new HashMap<>();
//                    m.put("name",item.getName());
//                    m.put("age",item.getAge());
//                    return m;
//                })
//                .forEach(System.out::println);

        //对流中元素排房
//        personList.stream()
//                .sorted((o1, o2) -> o1.getAge()- o2.getAge())
//                .forEach(System.out::println);


        //1)找到年龄大于20岁的人并输出;
        // filter()过滤器需要一个断言接口函数,断言接口返回true,获取该元素. foreach(Consumer)
        //无论执行多少个中间操作,如果没有执行终止操作,那么中间操作都不会被执行。
//        personList.stream()
//                .filter(item->item.getAge()>20)
//                .forEach(System.out::println);
        //2)找出所有中国人的数量.--->filter过滤掉其他国家的人 count()终止操作
//        long count = personList.stream()
//                .filter(item -> item.getCountry().equals("中国")).count();
//        System.out.println(count);
    }
}
class Person {
    private String name;
    private Integer age;
    private String country;
    private char sex;

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public char getSex() {
        return sex;
    }

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

    public Person(String name, Integer age, String country, char sex) {
        this.name = name;
        this.age = age;
        this.country = country;
        this.sex = sex;
    }
}

3. 新增了日期时间类

旧的日期时间的缺点:

  1. 设计比较乱: Date日期在java.util和java.sql也有,而且它的时间格式转换类在java.text包。

  2. 线程不安全。

新增加了哪些类?

LocalDate: 表示日期类。yyyy-MM-dd

LocalTime: 表示时间类。 HH:mm:ss

LocalDateTime: 表示日期时间类 yyyy-MM-dd t HH:mm:ss sss

DatetimeFormatter:日期时间格式转换类。

Instant: 时间戳类。

Duration: 用于计算两个日期类

package com.zsb.demo08;

import javax.swing.text.DateFormatter;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Test02 {
    public static void main(String[] args) {
        //获得当前日期
        LocalDate now = LocalDate.now();
        LocalDate date = LocalDate.of(2000,11,11);

        //获得当前时间
        LocalTime now1 = LocalTime.now();
        LocalTime date1 = LocalTime.of(15,44,58,985);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate p = LocalDate.parse("1899-11-12",dateTimeFormatter);
        String format = p.format(dateTimeFormatter);

        LocalTime now2 = LocalTime.now();
        LocalTime date2 = LocalTime.of(15,44,58,985);
        Duration batween = Duration.between(now2,date2);
        System.out.println(batween.toDays());


        LocalDateTime now4 = LocalDateTime.now();//获取当前日期时间
        LocalDateTime now3 = LocalDateTime.of(2022,6,20,17,45,20);
        Duration between = Duration.between(now4, now3);
        System.out.println(between.toHours());
    }
}

4.练习

交易员类
public class Trader {
    private final String name;
    private final String city;

    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Trader{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

Transaction(交易记录)

public class Transaction {
    private final Trader trader;
    private final int year;
    private final int value;
    public Transaction(Trader trader, int year, int value){
        this.trader = trader;
        this.year = year;
        this.value = value;
    }
    public Trader getTrader(){
        return this.trader;
    }
    public int getYear(){
        return this.year;
    }
    public int getValue(){
        return this.value;
    }
    public String toString(){
        return "{" + this.trader + ", " +
                "year: "+this.year+", " +
                "value:" + this.value +"}";
    }
}
        Trader raoul = new  Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");

        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

(1) 找出2011年发生的所有交易,并按交易额排序(从低到高)。
(2) 交易员都在哪些不同的城市工作过?
(3) 查找所有来自于剑桥的交易员,并按姓名排序。
(4) 返回所有交易员的姓名字符串,按字母顺序排序。
(5) 有没有交易员是在米兰工作的?
(6) 打印生活在剑桥的交易员的所有交易额。
(7) 所有交易中,最高的交易额是多少?
(8) 找到交易额最小的交易。

package com.zsb.demo09;


import java.util.*;

public class Test {
    public static void main(String[] args) {
        Test test = new Test();
        Trader raoul = new  Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");

        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );
//        (1) 找出2011年发生的所有交易,并按交易额排序(从低到高)。
        System.out.println("(1) 找出2011年发生的所有交易,并按交易额排序(从低到高)。");
        transactions.stream()
                .filter(item->item.getYear() ==2011)
                .sorted(((o1, o2) -> o1.getValue()- o2.getValue()))
                .forEach(System.out::println);
//        (2) 交易员都在哪些不同的城市工作过?
        System.out.println("(2) 交易员都在哪些不同的城市工作过?");
        transactions.stream()
                .map(item->item.getTrader().getCity())
                .distinct()
                .forEach(System.out::println);
//        (3) 查找所有来自于剑桥的交易员,并按姓名排序。
        System.out.println("(3) 查找所有来自于剑桥的交易员,并按姓名排序。");
        transactions.stream()
                .filter(item->item.getTrader().getCity().equals("Cambridge"))
                .map(Transaction::getTrader)
                .distinct()
                .sorted(Comparator.comparing(Trader::getName))
                .forEach(System.out::println);
//        *(4) 返回所有交易员的姓名字符串,按字母顺序排序。
        System.out.println("(4) 返回所有交易员的姓名字符串,按字母顺序排序。");
        transactions.stream()
                .map(item -> item.getTrader().getName())
                .distinct()
                .sorted()
                .forEach(System.out::println);
//        (5) 有没有交易员是在米兰工作的?
        System.out.println("(5) 有没有交易员是在米兰工作的?");
        boolean milan = transactions.stream()
                .anyMatch(item -> item.getTrader().getCity().equals("Milan"));
        System.out.println(milan);
//        (6) 打印生活在剑桥的交易员的所有交易额。
        System.out.println("(6) 打印生活在剑桥的交易员的所有交易额。");
        Optional<Integer> reduce = transactions.stream()
                .filter(item->item.getTrader().getCity().equals("Cambridge"))
                .map(item -> item.getValue())
                .reduce((a, b) -> a + b);
        System.out.println(reduce.get());
//        (7) 所有交易中,最高的交易额是多少?
        System.out.println("(7) 所有交易中,最高的交易额是多少?");
        Optional<Transaction> max = transactions.stream().max((o1, o2) -> o1.getValue() - o2.getValue());
        System.out.println(max.get());
//        (8) 找到交易额最小的交
        System.out.println("(8) 所有交易中,最小的交易额是多少?");
        Optional<Transaction> min = transactions.stream().min((o1, o2) -> o1.getValue() - o2.getValue());
        System.out.println(min.get());
    }
}
//交易员类
 class Trader {
    private final String name;
    private final String city;

    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Trader{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

//Transaction(交易记录)

 class Transaction {
    private final Trader trader;
    private final int year;
    private final int value;
    public Transaction(Trader trader, int year, int value){
        this.trader = trader;
        this.year = year;
        this.value = value;
    }
    public Trader getTrader(){
        return this.trader;
    }
    public int getYear(){
        return this.year;
    }
    public int getValue(){
        return this.value;
    }
    public String toString(){
        return "{" + this.trader + ", " +
                "year: "+this.year+", " +
                "value:" + this.value +"}";
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值