Stream Api一览

Stream

​ Java8中有两大最为重要的改变。第一个是Lambda表达式;另外一个则是Stream API(java.uti1.stream.*)。
Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用Stream API来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

什么是Stream

流(Stream)到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
“集合讲的是数据,流讲的是计算!”
注意:
①Stream 自己不会存储元素。
②Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream的操作三个步骤

·创建Stream

一个数据源(如:集合、数组),获取一个流
·中间操作
一个中间操作链,对数据源的数据进行处理
·终止操作(终端操作)

一个终止操作,执行中间操作链,并产生结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PmduXoHK-1600353064402)(E:\自我总结\java8\image\stream.png)]

创建stream四种方法

1.可以通过Collection系列集合提供的 stream()或parallelStream()

2.通过Arrays中的静态方法stream()获取数组流

3.通过Stream类中的静态方法of()

4.创造无限流

        //1.可以通过Collection系列集合提供的 stream()或parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
        //2.通过Arrays中的静态方法stream()获取数组流
        Employee[] emps = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(emps);
        //3.通过Stream类中的静态方法of()
        Stream<String> stream3 = Stream.of("aa", "bb", "cc");
        //4.创建无限流
        //迭代
        Stream<Integer> stream4 = Stream.iterate(1, (x) -> x + 2);
        //生成
        Stream.generate(()->Math.random()).limit(5).forEach(System.out::println);

Stream的中间操作

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

筛选与切片

方法描述
filter(Predicate p)接收Lambda,从流中排除某些元素。
distinct()筛选,通过流所生成元素的hashCode()和equals)去除重复元素
limit(long maxSize)截断流,使其元素不超过给定数量。
skip(long n)跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与1imit(n)互补
 /**
     * 筛选与切片
     * filter—接收Lambda,从流中排除某些元素。
     * 1imit—截断流,使其元素不超过给定数量。
     * skip(n)-跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与1imit(n)互补distinct-筛选,通过流所生成元素的hashCode()和equals()去除重复元素
     */
    List<Employee> emps = Arrays.asList(
            new Employee(101, "张三", 18, 9999.99),
            new Employee(102, "李四", 59, 6666.66),
            new Employee(103, "王五", 28, 3333.33),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(105, "田七", 38, 5555.55)
    );

    @Test
    public void test2() {
    	//内部迭代:迭代操作由Stream API完成
        //中间操作不会有任何结果  惰性求值 延迟加载
        //map阶段
        Stream<Employee> stream = emps.stream().filter(x -> x.getAge() > 35);
        //reduce阶段
        stream.forEach(System.out::println);
    }
    
执行结果:
	Stream API的中间操作
	Stream API的中间操作
	Employee [id=102, name=李四, age=59, salary=6666.66]
	Stream API的中间操作
	Stream API的中间操作
	Stream API的中间操作
	Employee [id=105, name=田七, age=38, salary=5555.55]
	
	@Test
    public void test3() {
        emps.stream().filter(e -> 				  e.getSalary()>5000).limit(2).forEach(System.out::println);
    }
    
    @Test
    public void test4(){
    	//分页使用
        emps.stream().skip(2).limit(2).forEach(System.out::println);
    }
    
    @Test
    public void test5(){
    	//去重
        emps.stream().distinct().forEach(System.out::println);
    }

映射

map—接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap—接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

	 @Test
    public void test6() {
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
        //map—接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,
        // 该函数会被应用到每个元素上,并将其映射成一个新的元素。
        list.stream().map((str)->str.toUpperCase()).forEach(System.out::println);
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        emps.stream().map(Employee::getName).forEach(System.out::println);
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //扁平化 flatMap将多个流整合成一个流 类似于list中的add 和 addAll
        Stream<Stream<Character>> streamStream = 	list.stream().map(this::filterCharacter);
        Stream<Character> characterStream = list.stream().flatMap(this::filterCharacter);
        characterStream.forEach(System.out::println);
    }

    public Stream<Character> filterCharacter(String str){
        List<Character> list = new ArrayList<>();
        for (Character c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

排序

sorted()–自然排序
sorted(Comparator com)—定制排序

@Test
    public void test7(){
        //自然排序
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
        list.stream().sorted().forEach(System.out::println);
        //定制排序
        emps.stream().sorted((e1,e2)->{
            if(e1.getAge() == e1.getAge()){
                return Double.compare(e1.getSalary(),e2.getSalary());
            }else {
                return Integer.compare(e1.getAge(),e2.getAge());
            }
        }).forEach(System.out::println);
    }

查找与匹配

allMatch—检查是否匹配所有元秦
anyMatch—检查是否至少匹配一个元素
noneMatch一检查是否没有匹配所有元素
findFirst—返回第一个元素
findAny-一返国当前淡中的任意元索
count一返回流中元系的总个数
max—返回流中最大值
min—返回流中最小值

@Test
    public void test8(){
        boolean b1 = emps.stream().allMatch(x -> x.getId() == 101);
        System.out.println(b1);
        boolean b2 = emps.stream().anyMatch(x -> x.getId() == 101);
        System.out.println(b2);
        boolean b3 = emps.stream().noneMatch(x -> x.getId() == 101);
        System.out.println(b3);
        Optional<Employee> first = emps.stream().findFirst();
        System.out.println(first);
        long count = emps.stream().count();
        System.out.println(count);
        Optional<Employee> max = emps.stream().max(Comparator.comparingInt(Employee::getAge));
        System.out.println(max);
    }

规约

reduce(T identity,BinaryOperator)/reduce(BinaryOperator)-可以将流中元反复结合起来,得到一个值。

@Test
    public void test9() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        //0为x的初始值
        Integer reduce = list.stream().reduce(0, (x, y) -> x + y);
        System.out.println(reduce);
    }

收集

collect—将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素散汇总的方法

@Test
    public void test10() {
        //平均值
        Double collect = emps.stream().collect(Collectors.averagingInt(Employee::getAge));
        System.out.println(collect);
        //总和
        Integer collect1 = emps.stream().collect(Collectors.summingInt(Employee::getAge));
        System.out.println(collect1);
        //最大值
        Optional<Employee> collect2 = emps.stream()
                .collect(Collectors.maxBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));
        System.out.println(collect2);
        //最小值
        Optional<Employee> collect3 = emps.stream().collect(Collectors.minBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));
        System.out.println(collect3);
    }
    //分组
        Map<Integer, List<Employee>> collect4 = emps.stream().collect(Collectors.groupingBy(Employee::getAge));
        System.out.println(collect4);
        Map<Boolean, List<Employee>> collect5 = emps.stream().collect(Collectors.partitioningBy(employee -> employee.getSalary() > 5000));
        System.out.println(collect5);
        //join
        String collect6 = emps.stream().map(Employee::getName).collect(Collectors.joining(",", "====", "==="));
        System.out.println(collect6);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值