Stream

什么是Stream?

Stream是java8的新特性,它允许你以声明式的方式处理数据集合,可以把它看作是遍历数据集的高级迭代器
此外stream与lambada表达式结合后编码效率大大提高,并且可读性更强

要澄清的是java8中的stream与InputStream和OutputStream是完全不同的概念

简单案例:
苹果类

package com.ffyc.java8up.stream;

public class Apple {
    private Integer num;
    private String color;
    private String state;

    public Apple(Integer num, String color, String state) {
        this.num = num;
        this.color = color;
        this.state = state;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "num=" + num +
                ", color='" + color + '\'' +
                ", state='" + state + '\'' +
                '}';
    }
}

public class Demo1 {
    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "red", "64G"));
        appleList.add(new Apple(2, "red", "64G"));
        appleList.add(new Apple(3, "green", "128G"));
        appleList.add(new Apple(4, "green", "128G"));
        appleList.add(new Apple(5, "yellow", "256G"));
        appleList.add(new Apple(6, "yellow", "256G"));

        /*
         * 我们的需求是在appleList中找到红色的苹果
         * 使用Stream快速操作*/
        List<Apple> list = appleList.stream()
                .filter(apple -> apple.getColor().equals("red"))
                .collect(Collectors.toList());
        System.out.println(list);
    }
}

输出结果
在这里插入图片描述


这就是java8中的stream流,使用的是声明性方式写的:说明想要完成什么(筛选,排序,取值),而不说明如何实现一个操作(for循环)同时可以将这些操作链接起来,从而达到一种流水线式的效果:
在这里插入图片描述
java8中的集合支持一个新的Stream方法,它会返回一个流

什么是流?

简单的定义:就是从支持数据处理错做的源,生成的元素序列

  • 元素列表: 和集合一样,流也提供了一个接口,访问特定元素类型的一组有序值。
  • 数据源: 获取数据的源,比如集合
  • 数据处理操作 流更偏向于数据处理和计算,比如filter、map、find、sort 等。

简单来说,我们通过一个集合的Stream方法获取一个流,然后对流进行一系列的流操作,最后再构建成我们需要的数据集合。

语法

stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|+
List<Integer> list =
					widgets.stream()
					.filter(b -> b.getColor() == RED)
					.sorted((x,y) -> x.getWeight() - y.getWeight())
					.sum();


获取流

  • 使用Collection接口下的stream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
  • 使用 Arrays 中的 stream() 方法,将数组转成流
Integer[] nums = new Integer[10];
Stream<Integer> stream = Arrays.stream(nums);
  • 使用 Stream 中的静态方法:of()
 Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6);
  • 使用BufferedReader.lines()方法,将每行内容转成流
 BufferedReader reader=new BufferedReader(new FileReader("stream.txt"));
 Stream<String> stream3 = reader.lines();

操作流

流操作可以分为两类:中间操作终端操作

List<Apple> apples = applestore
.stream() 获得流
.filter(a -> a.getColor().equals("red")) 中间操作
.collect(Collectors.toList()); 终端操作

简化一下就是:

数据源=> 中间操作 =>终端操作 =>结果

诸如 filter 或者 sort 等中间操作会返回另一个流,进而进行下一步流操作,而终端操作则是将流关闭,构建新的数据集合对象(也可以不构建)


中间操作

filter过滤流中的某些元素
sorted()自然排序,流中元素需实现 Comparable 接口
distinct去除重复元素
limit(n)获取 n 个元素
skip(n)跳过n元素,配合limit(n)可以实现分页
map()将其映射成一个新元素

代码演示:
filter:过滤流中的某些元素

public class MiddleOperation {
    public static void main(String[] args) {
        //filter:过滤流中的某些元素,
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7).filter(e -> e > 4);
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述
sorted(): 自然排序,流中元素需实现 Comparable 接口

  • 从小到大
public class MiddleOperation {
    public static void main(String[] args) {
      
        Stream<Integer> integerStream = Stream.of(5, 3, 2, 4, 1, 9, 7,6)
                //从小到大排序
                    .sorted();
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述

  • 从大到小
public class MiddleOperation {
    public static void main(String[] args) {
      
        Stream<Integer> integerStream = Stream.of(5, 3, 2, 4, 1, 9, 7,6)
                //从大到小排序
                  .sorted((o1, o2) -> o2-o1);
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述
distinct: 去除重复元素

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

        Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 2, 3, 3,4)
                .distinct();
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述
limit(n): 获取 n 个元素

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

        Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 2, 3, 3,4)
        .limit(4);
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述
skip(n): 跳过 n 元素,配合 limit(n)可实现分

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

        Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 2, 3, 3,4)
                .skip(6);
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述

  • 分页
public class MiddleOperation {
    public static void main(String[] args) {

        Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 2, 3, 3,4)
               .skip(2)
                .limit(3);
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述
map(): 将其映射成一个新的元素
将某个值映射到stream中去

package com.ffyc.java8up.stream;

public class Apple {
    private Integer num;
    private String color;
    private String state;

    public Apple(Integer num, String color, String state) {
        this.num = num;
        this.color = color;
        this.state = state;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "num=" + num +
                ", color='" + color + '\'' +
                ", state='" + state + '\'' +
                '}';
    }
}

public class Demo2 {
    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "red", "64G"));
        appleList.add(new Apple(2, "red", "64G"));
        appleList.add(new Apple(3, "green", "128G"));
        appleList.add(new Apple(4, "green", "128G"));
        appleList.add(new Apple(5, "yellow", "256G"));
        appleList.add(new Apple(6, "yellow", "256G"));

        /*
        中间操作map
        将某个值映射到stream中去
         */
        appleList.stream()
                .map(Apple::getColor)
                .forEach(integer -> System.out.println(integer));

    }
}

将苹果颜色映射到流中去
在这里插入图片描述

终端操作

forEach: 遍历流中的元素

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

        Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 2, 3, 3,4);
        integerStream.forEach(integer -> System.out.println(integer));
    }
}

在这里插入图片描述
toArray:将流中的元素倒入一个数组

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

     Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 2, 3, 3,4);
        Object[] objects = integerStream.toArray();
        System.out.println(Arrays.toString(objects));
    }
}

在这里插入图片描述
max:返回流中元素最大值

public class MiddleOperation {
    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(1, 3, 1, 4, 5, 2, 1);
        Integer max = integerStream.max((o1, o2) -> o1 - o2).get();
        System.out.println(max);
    }
}

在这里插入图片描述
Min:返回流中元素最小值

public class MiddleOperation {
    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(1, 3, 1, 4, 5, 2, 1);
        Integer min = integerStream.min((o1, o2) -> o1 - o2).get();
        System.out.println(min);
	}
}

在这里插入图片描述

count:返回流中元素的总个数

public class MiddleOperation {
    public static void main(String[] args) {
      
        Stream<Integer> integerStream = Stream.of(1, 3, 1, 4, 5, 2, 1);
        long count = integerStream.count();
        System.out.println(count);
    }
}

在这里插入图片描述
Reduce:所有元素求和

public class MiddleOperation {
    public static void main(String[] args) {
       Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
        Integer integer = integerStream.reduce((o1, o2) -> o1 + o2).get();
        System.out.println(integer);
    }
}

在这里插入图片描述

anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足条件则返回 true,否则返回 fals

public class MiddleOperation {
    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
        boolean anyMatch = integerStream.anyMatch(integer -> integer == 5);
        System.out.println(anyMatch);
    }
}

在这里插入图片描述
allMatch:接收一个 Predicate 函数,当流中每个元素都符合条件时才返
回 true,否则返回 fals

public class MiddleOperation {
    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
        boolean allMatch = integerStream.allMatch(integer -> integer == 5);
        System.out.println(allMatch);
    }
}

在这里插入图片描述
findFirst:返回流中第一个元素

public class MiddleOperation {
    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(5, 3, 2, 4, 1, 9, 7,6);
        System.out.println(integerStream.findFirst().get());

    }
}

在这里插入图片描述
collect:将流中的元素倒入一个集合,Collection 或 Map

  • tolist
package com.ffyc.java8up.stream;

public class Apple {
    private Integer num;
    private String color;
    private String state;

    public Apple(Integer num, String color, String state) {
        this.num = num;
        this.color = color;
        this.state = state;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "num=" + num +
                ", color='" + color + '\'' +
                ", state='" + state + '\'' +
                '}';
    }
}

public class Demo2 {
    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "red", "64G"));
        appleList.add(new Apple(2, "red", "64G"));
        appleList.add(new Apple(3, "green", "128G"));
        appleList.add(new Apple(4, "green", "128G"));
        appleList.add(new Apple(5, "yellow", "256G"));
        appleList.add(new Apple(6, "yellow", "256G"));

        List<Apple> collect = appleList.stream()
                .sorted(((o1, o2) -> o2.getNum()-o1.getNum()))
                .collect(Collectors.toList());
        System.out.println(collect);

    }
}

在这里插入图片描述

  • toSet
public class Demo2 {
    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "red", "64G"));
        appleList.add(new Apple(2, "red", "64G"));
        appleList.add(new Apple(3, "green", "128G"));
        appleList.add(new Apple(4, "green", "128G"));
        appleList.add(new Apple(5, "yellow", "256G"));
        appleList.add(new Apple(6, "yellow", "256G"));

     Set<Apple> collect = appleList.stream()
        .collect(Collectors.toSet());
        System.out.println(collect);

    }
}

在这里插入图片描述

  • toMap
public class Demo2 {
    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "red", "64G"));
        appleList.add(new Apple(2, "red", "64G"));
        appleList.add(new Apple(3, "green", "128G"));
        appleList.add(new Apple(4, "green", "128G"));
        appleList.add(new Apple(5, "yellow", "256G"));
        appleList.add(new Apple(6, "yellow", "256G"));

   Map<Integer, String> collect = appleList.stream().
                collect(Collectors.toMap(Apple::getNum, Apple::getColor));
        System.out.println(collect);

    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值