Stream流中间操作举例

  1. 过滤、截断、跳过、去重
    代码中都有注释

    	@Test
        public void test() {
            Student[] students = new Student[] { new Student("a", 1), new Student("b", 2),
                    new Student("c", 3), new Student("d", 4), new Student("e", 5) };
            // Stream流中间操作---过滤
            Arrays.asList(students).stream().filter(s -> s.getAge() > 3).forEach(System.out::println);
            System.out.println("*********************************");
            // Stream流中间操作---截断(取前几个数据)
            Arrays.asList(students).stream().limit(3).forEach(System.out::println);
            System.out.println("*********************************");
            // Stream流中间操作---跳过(跳过前面几个数据)
            Arrays.asList(students).stream().skip(3).forEach(System.out::println);
            System.out.println("*********************************");
            // Stream流中间操作---去重(根据equal和hashcode判断)
            Arrays.asList(students).stream().distinct().forEach(System.out::println);
        }
    

    这些都是常规操作比较容易理解

  2. 映射map和flatMap
    推荐我的另一篇博客
    Stream流中间操作之map和flatMap的区别

  3. 排序

    	@Test
        public void test3(){
            Student[] students = new Student[] { new Student("a.a", 1), new Student("b.b", 2),
                    new Student("c.c", 3), new Student("d.d", 4), new Student("e.e", 5) };
            // 报错,Student类没有默认的排序方法(没有实现Comparable接口)
            //Arrays.asList(students).stream().sorted().forEach(System.out::println);
            System.out.println("*********************************");
            // Integer实现了Comparable接口,有默认排序方法
            Arrays.asList(students).stream().map(Student::getAge).sorted().forEach(System.out::println);
            System.out.println("*********************************");
            // 自定义比较器,传入一个Comparator的函数式接口
            Arrays.asList(students).stream().sorted((x,y)->Integer.compare(x.getAge(),y.getAge())).forEach(System.out::println);
            // 推荐写法,效果跟上面的还是一样的
            Arrays.asList(students).stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);
    }
    

    sort()没有参数的排序方法,会采取当前类的默认排序方法(需要该类实现Comparable接口,不然报错)
    sorted(Comparator<? super T> comparator),传入一个Comparator的函数式接口,来自定义排序

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值