java8——Stream

本文深入讲解Java Stream API的使用,包括Stream的创建方法、中间操作如筛选、映射和排序,以及终止操作如查找、归约和收集。通过示例演示如何利用Stream API简化集合操作,提高代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建Stream

 @Test
    public void test1(){
        //1. 可以通过Collection系列集合提供的Stream()或 parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> s1 = list.stream();
        // 2. 通过Arrays中的静态方法stream()获取数组流
        Employee[] e = new Employee[10];
        Stream<Employee> s = Arrays.stream(e);
        // 3. 通过Stream类的静态方法 of()
        Stream<String> s3 =Stream.of("aa","sd");
        //4 .创建无限流
        //4.1 迭代
        Stream<Integer> s4 = Stream.iterate(0,(x)->x+2);
        s4.limit(3).forEach(System.out::println);
        // 4.2 生成
        Stream<Double> s5 = Stream.generate((()->Math.random()));
        s5.limit(5).forEach(System.out::println);
    }

2. 中间操作

多个中间操作可以连接起来形成一个流水线,出发触发终止操作,否则中间操作不会执行任何的处理,在终止操作是一次性处理,称为惰性求值或延迟加载

2.1 筛选和切片

  • filter - 接收Lambda,从流中排除某些元素
  • limit- 截断流
  • skip(n) - 跳过元素,返回一个去除前n个元素的流,当流中元素不足n时返回空流
  • distinct - 筛选,通过流生成的元素的hashCode() 和 equals去重
   private List<Employee> employees = Arrays.asList( new Employee("小王",23,"111"),new Employee("小王",23,"111"),new Employee("小王",23,"111"), new Employee("哈哈",100,"111"),new Employee("哈哈",11,"111"));
    /*
    筛选与切片
    filter - 接收Lambda,从流中排除某些元素
    limit- 截断流
    skip(n) - 跳过元素,返回一个去除前n个元素的流,当流中元素不足n时返回空流
    distinct - 筛选,通过流生成的元素的hashCode() 和 equals去重
     */
    @Test
    public void test2(){
        Stream<Employee> stream = employees.stream();
        Stream<Employee> fs = stream.skip(1).distinct().filter((x)->x.getYear()<35).limit(2);
        //没有终止操作时,中间操作不执行
        fs.forEach(System.out::println);
    }
    /*
    Emloyee{name='小王', year='23', position='111'}
	Emloyee{name='小王', year='23', position='111'}
	*/

2.2 映射

  • map–接收lambda函数,将该函数作为参数,应用到每个元素上,并映射成一个新的元素,返回一个新的流
  • flatMap – 接收一个函数作为参数,将流中的每个值都转换成另一个流,然后将所有流连接成一个流
    @Test
    public void test3(){
        list.stream().map((s)->s.toUpperCase()).forEach(System.out::println);
        employees.stream().map(Employee::getName).forEach(System.out::println);
        
        Stream<Stream<Character>> s= list.stream().map(TestStreamAPI::filter);
        s.forEach((x)->x.forEach(System.out::println));
        Stream<Character> s3 = list.stream().flatMap(TestStreamAPI::filter);
        s3.forEach(System.out::println);
    }

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

2.3 排序

  • sorted-自然排序,按照comparable方式排序
  • sorted(Comparator com)–定制排序
@Test
    public void test4(){
    	List<String> list = Arrays.asList("aa","bb","c");
        list.stream().sorted().forEach(System.out::println);
        employees.stream()
                .sorted((e1,e2)->{
                    if (e1.getYear()==e2.getYear())
                        return e1.getName().compareTo(e2.getName());
                    else
                       return Integer.compare(e1.getYear(),e2.getYear());
                }).forEach(System.out::println);
    }

终止操作

3.1 查找和匹配

  • boolean allMatch 是否匹配所有元素
  • boolean anyMatch 是否至少匹配一个元素
  • boolean nonMatch 是否没有匹配所有的元素
  • Optional findFirst
  • Optional findAny
  • Long count
  • Optional max
  • Optional min
@Test
    public void test5(){
        boolean b1 = employees.stream().allMatch(e->e.getName().equals("11"));
        System.out.println(b1);
        boolean b2 = employees.stream().anyMatch(e->e.getName().equals("小王"));
        System.out.println(b2);
        boolean b3 = employees.stream().noneMatch(e->e.getName().equals("小王"));
        System.out.println(b3);

        Optional<Employee> oe1 = employees.stream()
                .sorted((e1,e2)->e1.getYear().compareTo(e2.getYear()))
                .findFirst();
        System.out.println(oe1.get());

        Optional<Employee> oe2 = employees.stream().filter(e->e.getYear()>22).findAny();
        System.out.println(oe2.get());
    }

3.2 归约

归约–将流中元素反复结合得到新值

  • T reduce(T identity,BinaryOperator)
  • Optional reduce(BinaryOperator)
  • 可能为空的情况下返回值为Optional

    @Test
    public void test6(){
        List<Integer> list = Arrays.asList(1,3,4,5);
        Integer sum  = list.stream().reduce(0,(x,y)->x+y);
        System.out.println(sum);
        Optional<String> oes = employees.stream().map(Employee::getName).reduce((s1,s2)->s1.concat(s2));
        System.out.println(oes.get());
    }
    

3.3 收集

collect – 将流转换成其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总

    @Test
    public void test7(){
        // 收集某项信息的集合
        List<String> list = employees.stream().map(Employee::getName).collect(Collectors.toList());
        list.forEach(System.out::println);
        System.out.println("------------------------");
        HashSet<String> set = employees.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
        set.forEach(System.out::println);
        //总数
        Long count =employees.stream().collect(Collectors.counting());
        //平均值
        Double agv = employees.stream().collect(Collectors.averagingInt(Employee::getYear));
        //总和
        Long sum = employees.stream().collect(Collectors.summingLong(Employee::getYear));
        //最大值
        Optional<Employee> max = employees.stream().collect(Collectors.maxBy((e1,e2)->Integer.compare(e1.getYear(),e2.getYear())));
        // 最小值
        Optional<Employee> min = employees.stream().collect(Collectors.minBy((e1,e2)->Integer.compare(e1.getYear(),e2.getYear())));
        System.out.println(count+" "+ agv+" "+max.get()+" "+min.get());
        // 分组
        Map<String,List<Employee>> p2E = employees.stream().collect(Collectors.groupingBy(Employee::getPosition));
        System.out.println(p2E);
        // 多级分组
        Map<String, Map<String, List<Employee>>> p2ae = employees.stream()
                .collect(Collectors.groupingBy(Employee::getPosition,
                        Collectors.groupingBy((e)->{
                            if (((Employee)e).getYear()<35)
                                return "青年";
                            return "中年";

        })));
        System.out.println(p2ae);
        //分区
        Map<Boolean,List<Employee>> bes = employees.stream().collect(Collectors.partitioningBy(e->e.getYear()>30));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值