基本数据类型优化

HeJin小于 1 分钟函数式编程高级用法

public static void main(String[] args) throws Throwable {
    List<Author> authors = getAuthors();

    authors.stream()
            .map(Author::getAge)
            .map(age -> age + 10)
            .filter(age -> age > 18)
            .map(age -> age + 2)
            .forEach(System.out::println);
}

上面的代码计算过程中有自动拆装箱操作,如果数据量很大,会严重影响性能。

stream专门提供了很多针对基本数据类型优化的方法。例如mapToInt、mapToLong、flatMapToInt等。

public static void main(String[] args) throws Throwable {
    List<Author> authors = getAuthors();

    authors.stream()
            .mapToInt(Author::getAge)
            .map(new IntUnaryOperator() {
                @Override
                public int applyAsInt(int operand) {
                    return operand + 10;
                }
            })
            .filter(age -> age > 18)
            .map(age -> age + 2)
            .forEach(System.out::println);
}