stream的优化:java封装的拆箱与装箱的弊端

发布时间 2023-12-26 20:56:10作者: 天启A
authors.stream()
    .map(author->author.getAge)
    .map(age->age+10)//Stream<Integer>
    .filter(age>18)//Stream<Integer>
    .foreach(System.out::println);

上述是一个简单的stream流的使用,当我们拆开第二个map,或者filter的时候会发现,传入和传出的参数都是Integer类型,这样的拆箱与装箱无疑会增大时间的损耗,

为此stream提供了一些基本数据类型的优化

authors.stream()
    .mapToInt(author->author.getAge)
    .map(age->age+10)//IntStream
    .filter(age>18)//IntStream
    .foreach(System.out::println);

还有其他的形式:mapToLong,mapToDouble,flatMapToInt等等