JAVA stream API

什么是stream

流(Stream)是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
集合讲的是数据,流讲的是计算

注意:
Stream自己不会存储数据
Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream
Stream操作时延迟执行的,这意味着他们会等到需要结果的时候才执行

Stream操作的三个步骤

创建Stream
中间操作:一个中间操作链,对数剧源的数据进行处理
终止操作:执行中间操作链,并产生结果

创建Stream

1.通过Collections系列集合提供的stream()或parallelStream()
Java8 中的 Collection 接口被扩展,提供了
两个获取流的方法:
default Stream<E> stream() : 返回一个顺序流
default Stream<E> parallelStream() : 返回一个并行流

        //通过Collections系列集合提供的stream()或parallelStream()
        ArrayList<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();

2.通过Arrays中的静态方法stream()获取数组流
Java8 中的 Arrays 的静态方法 stream() 可
以获取数组流:
static <T> Stream<T> stream(T[] array): 返回一个流
重载形式,能够处理对应基本类型的数组:
public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)

        //通过Arrays中的静态方法stream()获取数组流
        employee[] employees = new employee[10];
        Stream<employee> stream2 = Arrays.stream(employees);

3.通过Stream类中的静态方法of()
可以使用静态方法 Stream.of(), 通过显示值
创建一个流。它可以接收任意数量的参数。
public static<T> Stream<T> of(T... values) : 返回一个流

//通过Stream类中的静态方法of()
        Stream<String> stream3 = Stream.of("aa", "bb", "cc");

4.创建无限流,迭代 / 生成
可以使用静态方法 Stream.iterate() 和
Stream.generate(), 创建无限流。
迭代:public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
生成:public static<T> Stream<T> generate(Supplier<T> s)

        //创建无限流,迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.limit(10).forEach(System.out::println);//limit(10)是中间操作
        //创建无限流,生成
        Stream.generate(() -> Math.random()*10).limit(5).forEach(System.out::println);

中间操作

多个中间操作可以连接起来形成一个流水线,除非流水
线上触发终止操作,否则中间操作不会执行任何的处理!
而在终止操作时一次性全部处理,称为“惰性求值”

1.筛选与切片

//employee数组
   public static List<employee> emp = Arrays.asList(
            new employee("zzz", 25, 40000),
            new employee("rrr", 34, 30000),
            new employee("xxx", 22, 30000),
            new employee("xxx", 22, 30000),
            new employee("ddd", 22, 30000)
    );

filter(Predicate p) 接收 Lambda , 从流中排除某些元素。

   public static void test01(){
   		//内部迭代
        emp.stream().filter((e)->e.getAge()>22).forEach(System.out::println);
        System.out.println("===================");
        //外部迭代
        Iterator<employee> iterator = emp.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

limit(long maxSize) 截断流,使其元素不超过给定数量。

    public static void test02(){
        emp.stream().filter((e)->e.getSalary()>5000).limit(2).forEach(System.out::println);
        System.out.println("====================");
        emp.stream().filter((e)->e.getSalary()>5000).forEach(System.out::println);
    }

skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补

    public static void test03(){
        emp.stream().filter(e->e.getSalary()>5000).forEach(System.out::println);
        System.out.println("=======================");
        emp.stream().filter(e->e.getSalary()>5000).skip(2).forEach(System.out::println);
    }

distinct() 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

    public static void test04(){
        emp.stream().filter(e->e.getSalary()>5000).distinct().forEach(System.out::println);
        emp.stream().filter(e->e.getSalary()>5000).forEach(System.out::println);
    }

2.映射
map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。

    public static void test05(){
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
        list.stream().map(String::toUpperCase).forEach(System.out::println);
        emp.stream().map(e->e.getName()).forEach(System.out::println);
    }

mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

    public static void test07(){
        List<String> list = Arrays.asList("AAA", "BBB");
        Stream<Character> characterStream = list.stream().flatMap(streamAPI2::filterCharacter);
        //{A,A,A,B,B,B}
        characterStream.forEach(System.out::println);
    }
//等价于下面代码
    public static void test06(){
        List<String> list = Arrays.asList("AAA", "BBB");
        Stream<Stream<Character>> ss = list.stream().map(streamAPI2::filterCharacter);
        //{{A,A,A},{B,B,B}}
        ss.forEach(s->s.forEach(System.out::println));
    }
    public static Stream<Character> filterCharacter(String str){
        ArrayList<Character> list = new ArrayList<>();
        for (char c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

3.排序
sorted() 产生一个新流,其中按自然顺序排序

sorted(Comparator comp) 产生一个新流,其中按比较器顺序排序

    public static void test08(){
        List<String> list = Arrays.asList("eee", "bbb", "aaa", "ddd");
        list.stream().sorted().forEach(System.out::println);
        emp.stream().sorted((e1,e2)->Integer.compare(e1.getAge(),e2.getAge()))
                .forEach(System.out::println);
        System.out.println("++++++++++++++++++++++++");
        emp.stream().sorted((e1,e2)->{
            if (e1.getAge()==e2.getAge()) {
                return e1.getSalary().compareTo(e2.getSalary());
            }else return Integer.compare(e1.getAge(),e2.getAge());
        }).forEach(System.out::println);
    }

终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。
1.查找与匹配
allMatch(Predicate p) 检查是否匹配所有元素
anyMatch(Predicate p) 检查是否至少匹配一个元素
noneMatch(Predicate p) 检查是否没有匹配所有元素
findFirst() 返回第一个元素
findAny() 返回当前流中的任意元素

    public  static List<employee> emp = Arrays.asList(
            new employee("zzz", 25, 40000.0, employee.Status.FREE),
            new employee("rrr", 34, 20000.0, employee.Status.BUSY),
            new employee("xxx", 22, 30000.0, employee.Status.VOCATION),
            new employee("xxx", 22, 30000.0, employee.Status.FREE),
            new employee("ddd", 22, 10000.0, employee.Status.VOCATION)
    );
    public static void main(String[] args) {
        test01();
    }
    public static void test01(){
        boolean b = emp.stream().allMatch((e) -> e.getStatus().equals(employee.Status.BUSY));
        System.out.println(b);//false
        boolean b1 = emp.stream().anyMatch(e -> e.getStatus().equals(employee.Status.BUSY));
        System.out.println(b1);//true
        boolean b2 = emp.stream().noneMatch(e -> e.getStatus().equals(employee.Status.VOCATION));
        System.out.println(b2);//false
        Optional<employee> first = emp.stream().
                sorted((e1, e2) -> e2.getSalary().compareTo(e1.getSalary()))
                .findFirst();//若为空则封装到Optional容器中
        System.out.println(first);
        Optional<employee> first1 = emp.stream().
                sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
                .findFirst();
        System.out.println(first1);
        System.out.println(emp.parallelStream().
                filter(e->e.getStatus().
                        equals(employee.Status.FREE)).findAny());
    }

count() 返回流中元素总数
max(Comparator c) 返回流中最大值
min(Comparator c) 返回流中最小值

    public  static List<employee> emp = Arrays.asList(
            new employee("zzz", 25, 40000.0, employee.Status.FREE),
            new employee("rrr", 34, 20000.0, employee.Status.BUSY),
            new employee("xxx", 22, 30000.0, employee.Status.VOCATION),
            new employee("xxx", 22, 30000.0, employee.Status.FREE),
            new employee("ddd", 22, 10000.0, employee.Status.VOCATION)
    );
    public static void main(String[] args) {
        //test01();
        test02();
    }
    public static void test02(){
        long count = emp.stream().count();
        System.out.println(count);
        Optional<Double> max = emp.stream()
                .map(employee::getSalary)
                .max(Double::compare);
        System.out.println(max.get());
        Optional<employee> min = emp.stream()
                .min((e1, e2) -> e1.getAge().compareTo(e2.getAge()));
        System.out.println(min.get());
    }

forEach(Consumer c) 内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了

   public static void test01(){
   		//内部迭代
        emp.stream().filter((e)->e.getAge()>22).forEach(System.out::println);
        System.out.println("===================");
        //外部迭代
        Iterator<employee> iterator = emp.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

2.归约
reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 T
reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回Optional<T>

    public static void test03(){
        List<Integer> list = Arrays.asList(1, 3, 2, 4, 5, 6, 7, 8,0);
        Integer sum = list.stream().reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        Optional<Double> reduce = emp.stream().map(employee::getSalary).
                reduce(Double::sum);
        System.out.println(reduce.get());
    }

备注:map 和 reduce 的连接通常称为map-reduce 模式,因 Google 用它来进行网络搜索而出名。

3.收集
collect(Collector c) 将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法。

    public static void test04(){
        //提取名字放在集合中
        List<String> list = emp.stream().map(employee::getName).
                collect(Collectors.toList());
        list.forEach(System.out::println);
        System.out.println("=======================");
        //提取名字放在集合Set中 set去重
        Set<String> list1 = emp.stream().map(employee::getName).
                collect(Collectors.toSet());
        list1.forEach(System.out::println);
        System.out.println("=======================");
        //提取名字放在集合HashSet中
        Set<String> list2 = emp.stream().map(employee::getName).
                collect(Collectors.toCollection(HashSet::new));
        list1.forEach(System.out::println);
    }
   public static void test05(){
        //总数
        Long collect = emp.stream().collect(Collectors.counting());
        System.out.println(collect);
        //平均值
        Double avg = emp.stream()
                .collect(Collectors.averagingDouble(employee::getSalary));
        System.out.println(avg);
        //工资总和
        Double sum_sal = emp.stream().
                collect(Collectors.summingDouble(employee::getSalary));
        System.out.println(sum_sal);
        //最大值
        Optional<employee> collect1 = emp.stream().collect(Collectors.maxBy((e1, e2) -> e1.getSalary().compareTo(e2.getSalary())));
        System.out.println(collect1.get());
        //最小值
        Optional<Double> collect2 = emp.stream().map(employee::getSalary)
                .collect(Collectors.minBy(Double::compare));
        System.out.println(collect2.get());
        //所有值
        DoubleSummaryStatistics all = emp.stream().collect(Collectors
                .summarizingDouble(employee::getSalary));
        System.out.println(all);
    }
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值