java8 Stream 常用方法讲解

Java 8 Stream

java8 中新增了一种Stream流的特性,这种方式跟写SQL似的,一个集合看成一个数据表,Stream看成条件,然后返回一个新的数据。

Steam API 可以极大提高程序员的效率,可以让程序员写出高效,干净,简洁的代码,唯一一点不好的地方就是如果程序员不会这个你会看不懂。

如果需要看Lambda写法,请看另一篇

java8 Lambda表达式详细讲解

java8中有两种方法来生成流

  • 1. stream() -为集合创建串行流
  • 2. parallelStream() -为集合创建并行流

就是一个单线程,一个多线程的意思。

Stream执行特征

使用Stream操作集合和以前操作集合是不同的,Stream操作特征主要有两种

1. 管道流式处理数据。

2. 内部迭代。

就比如说我现在要筛选集合中年龄等于22的数据

原来做法是

     List<Person> list2 = new ArrayList<>();
       //先遍历-这叫外部循环
        for (Person person :personList){
            if (person.getAge() == 22){
                list2.add(person);
            }
        }

java8 stream做法是内部迭代,和上面这种实现方式是不一样的。

List<Person> collect1 = personList
                .stream()
                .filter(person -> person.getAge() == 22)
                .collect(Collectors.toList());

在效率上java8 stream是更快的

具体底层原理自己去翻,我这里就不讲了

接下来介绍stream 中各种常用的方法

  • filter  

    filter是一个过滤参数,可以通过增加一些条件来筛选数据        以下代码是筛选出年龄为22岁的人,获取的是条件返回true的数据 
        List<Person> collect1 = personList
                .stream()
                .filter(person -> person.getAge() == 22)
                .collect(Collectors.toList());

   结果是

[Person{name='wan9', age=22, birthDate=2009-01-03T09:31:20}]
  •  map

    map是可以映射到每个元素到对应结果的方法,就是可以对集合的每个结果进行操作,然后把这个结果的值返回,并生成一个集合

  如下是把当前集合中年龄数据取出来,并把所有年龄数据+1,并组合成一个集合返回。

List<Integer> collect = personList.stream()
                .map(person -> person.getAge() + 1)
                .collect(Collectors.toList());

结果为

操作数据前集合
[
Person{name='wan1', age=90, birthDate=2001-01-03T01:31:20}, 
Person{name='wan18', age=111, birthDate=2018-01-03T18:31:20}, 
Person{name='wan17', age=85, birthDate=2017-01-03T17:31:20}
]

新返回的集合
[91, 112, 86]

mapToInt、mapToLong、mapToDouble

这些方法返回的都是带有数据类型的stream ,只能做一些聚合类的结束操作,比如sum,min等

int sum = personList.stream().mapToInt(person -> person.getAge()).sum();
System.out.println(sum);

  •  limit

        limit 就是获取指定数量的流,就是取多少条数据,从前往后

        

List<Person> collect2 = personList
                .stream()
                .limit(2)
                .collect(Collectors.toList());

结果为

//操作前的数据
[
Person{name='wan4', age=78, birthDate=2004-01-03T04:31:20}, 
Person{name='wan17', age=10, birthDate=2017-01-03T17:31:20}, 
Person{name='wan0', age=57, birthDate=2000-01-03T00:31:20}
]
//操作后的数据
[
Person{name='wan4', age=78, birthDate=2004-01-03T04:31:20}, 
Person{name='wan17', age=10, birthDate=2017-01-03T17:31:20}
]

  •  skip

        skip是可以跳过当前多少个集合元素,返回后面的集合

 List<Person> collect3 = personList
                .stream()
                .skip(2)
                .collect(Collectors.toList());

 结果为

//操作前集合
[
Person{name='wan10', age=74, birthDate=2010-01-03T10:31:20}, 
Person{name='wan7', age=20, birthDate=2007-01-03T07:31:20}, 
Person{name='wan2', age=81, birthDate=2002-01-03T02:31:20}
]

//操作后集合

[Person{name='wan2', age=81, birthDate=2002-01-03T02:31:20}]

  •  sorted

         sorted 方法可以为集合元素排序

        把集合数据按年龄排序

        

        //正序
        List<Person> sorted = personList
                .stream()
                .sorted(Comparator.comparing(Person::getAge))
                .collect(Collectors.toList());
        //倒序
        List<Person> sorted2 = personList
                .stream()
                .sorted(Comparator.comparing(Person::getAge).reversed())
                .collect(Collectors.toList());

        还可以自定义排序规则

        

 List<Person> collect4 = personList.stream()
                .sorted(new Comparator<Person>() {
                    @Override
                    public int compare(Person o1, Person o2) {
                        return o1.getBirthDate().compareTo(o2.getBirthDate());
                    }
                })
                .collect(Collectors.toList());

  •  isParallel        

         判断当前流是否是并行流

        //串行流
        boolean parallel = list.stream().filter(people1 ->
                people1.getAge().equals(10)
        ).map(People::getName).isParallel();
        System.out.println(parallel);
        //并行流
        boolean parallel1 = list.parallelStream().isParallel();
        System.out.println(parallel1);

结果为

false
true
  •  distnct

        distanct 方法,可以用来给元素去重操作

        唯一需要注意得地方就是,如果是对象需要去重,需要重写hashcode方法和equals 方法来判断去重得,所以对象得重写这个方法,不然就会去重失败,其他的没啥,都比较简单。

        

List<Person> collect5 = personList
                .stream()
                .distinct()
                .collect(Collectors.toList());

       

流的终止操作

        聚合操作

        Stream中

        min

        max

        count

        

Stream<Integer> integerStream = personList.stream()
                .map(person -> person.getAge());
//统计数量
integerStream.count();
//获取最大值,但是需要传入比较值
Integer integer = integerStream.max(Comparator.comparing(Integer::intValue)).get();
//获取最小值,但是需要传入比较值
Integer integer1 = integerStream.min(Comparator.comparing(Integer::intValue)).get();

        带类型的Stream中:IntStream。。。。等等

        sum操作

 int sum1 = personList.stream()
                .mapToInt(Person::getAge).sum();

        收集操作

         collect   

         collect 这是一个收集流的方法

         Collectors 是Collector 类的工具类,对Collector进行了很多方法的封装

        

        收集类型

        Collectors.toList

        把流转化为list操作,默认为Arraylist

List<Person> collect6 = personList
                .stream()
                .collect(Collectors.toList());

  

        Collectors .toSet

        把流转化为Set,默认为HashSet

        

//toSet
Set<Person> collect9 = personList
                .stream()
                .collect(Collectors.toSet());

        Collectors .toMap

        把流转化为Map,默认类型为HashMap,默认类型里面就可以看到,里面定义了。

//toMap----age为key ,name为value
Map<Integer, String> collect7 = personList
                .stream()
                .collect(Collectors.toMap(Person::getAge, Person::getName));

常用的就这些了

创作不易,点个赞!

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风某人~Wind

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值