Java函数式编程-三更草堂-学习笔记

函数式编程思想

函数式编程思想类似于我们数学中的函数,它主要关注的是对数据进行了什么操作。

优点:

  • 代码简洁,开发快速
  • 接近自然语言,易于理解
  • 易于“并发编程”

Lambda表达式

Lambda是JDK8中一个语法糖,它可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现,让我们不用关注是什么对象,而是关注我们对数据进行了什么操作。

基本格式:
(参数列表) -> {代码}

例1:
我们在创建线程并启动时可以使用匿名内部类的写法

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("线程中run方法被执行");
    }
}).start();

Lambda表达式只关注有什么参数

new Thread(() -> {
        System.out.println("线程中run方法被执行");
}).start();

例2:

public static void main(String[] args) {
    int sum = calculateNum(new IntBinaryOperator() {
        @Override
        public int applyAsInt(int left, int right) {
            return left + right;
        }
    });
    System.out.println(sum);
}

// IntBinaryOperator为一个接口
public static int calculateNum(IntBinaryOperator operator) {
    int a = 10;
    int b = 20;
    return operator.applyAsInt(a, b);
}

匿名内部类 优化成Lambda表达式

public static void main(String[] args) {
    int sum = calculateNum((int left, int right) -> {
        return left + right;
    });
    System.out.println(sum);
}
//IntBinaryOperator为一个接口
public static int calculateNum(IntBinaryOperator operator) {
    int a = 10;
    int b = 20;
    return operator.applyAsInt(a, b);
}

例3:

public static void main(String[] args) {
    printNum(new IntPredicate() {
        @Override
        public boolean test(int value) {
            return value%2 == 0;
        }
    });
}

public static void printNum(IntPredicate predicate) {
    int[] arr = {1,2,3,4,5,6,7,8,9,10};
    for (int i : arr) {
        if (predicate.test(i)) {
            System.out.println(i);
        }
    }
}

优化

public static void main(String[] args) {
    printNum((int value) -> {
        return value%2 == 0;
    });
}

public static void printNum(IntPredicate predicate) {
    int[] arr = {1,2,3,4,5,6,7,8,9,10};
    for (int i : arr) {
        if (predicate.test(i)) {
            System.out.println(i);
        }
    }
}

例4:

public static void main(String[] args) {
    String str = typeConver(new Function<String, String>() {
        public String apply(String s) {
            return s + " hxp";
        }
    });
    System.out.println(str);
}

public static <R> R typeConver(Function<String,R> function) {
    String str = "hello";
    R result = function.apply(str);
    return result;
}

优化

public static void main(String[] args) {
    String str = typeConver((String s) -> {
        return s + " hxp";
    });
    System.out.println(str);
}

public static <R> R typeConver(Function<String,R> function) {
    String str = "hello";
    R result = function.apply(str);
    return result;
}

再省略

public static void main(String[] args) {
    String str = typeConver(s -> s + " hxp");
    System.out.println(str);
}

总结:使用Lambda表达式替换匿名内部类,只需要保留匿名内部类的方法参数和方法体,然后在中间加一个箭头即可。

省略规则

  • 参数类型可以省略
  • 方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
  • 方法只有一个参数时,小括号可以省略
  • 以上规则都可以省略不记,使用idea的快捷键 alt+enter

Stream流

Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作,可以更方便的让我们对集合或数组操作。

入门案例

案例准备:

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode  // 去重
public class Author {
    private Long id;
    private String name;
    private Integer age;
    private String intro;
    private List<Book> books;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Book {
    private Long id;
    private String name;
    private String category;
    private Integer score;
    private String intro;
}
public class StreamDemo {

    private static List<Author> getAuthors() {
        Author author = new Author(1L, "蒙多", 17, "一个祖安人", null);
        Author author2 = new Author(2L, "亚拉索", 18, "艾欧尼亚", null);
        Author author3 = new Author(3L, "易大师", 19, "黑色玫瑰", null);
        Author author4 = new Author(3L, "易大师", 19, "黑色玫瑰", null);

        List<Book> book1 = new ArrayList<>();
        List<Book> book2 = new ArrayList<>();
        List<Book> book3 = new ArrayList<>();
        List<Book> book4 = new ArrayList<>();

        book1.add(new Book(1L,"*","哲学,爱情", 80, "*"));
        book1.add(new Book(2L,"**","爱情,个人成长", 80, "**"));

        book2.add(new Book(3L,"***","爱情,传记", 70, "***"));
        book2.add(new Book(3L,"****","个人成长,传记", 70, "****"));
        book2.add(new Book(4L,"*****","哲学", 70, "*****"));

        book3.add(new Book(5L,"******","个人成长", 60, "******"));
        book3.add(new Book(6L,"*******","传记", 60, "*******"));
        book3.add(new Book(6L,"********","爱情", 60, "********"));

        book4.add(new Book(5L,"******","个人成长", 60, "******"));
        book4.add(new Book(6L,"*******","个人成长,传记,爱情", 60, "*******"));
        book4.add(new Book(6L,"********","哲学,爱情,个人成长", 60, "********"));


        author.setBooks(book1);
        author2.setBooks(book2);
        author3.setBooks(book3);
        author4.setBooks(book4);

        List<Author> authors = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
        return authors;
    }
}

案例:获取到作家的集合,打印出年龄小于18的作家的名字

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    authors.stream()    //将集合转换成流
            .distinct() //去重
            .filter(new Predicate<Author>() {
                @Override
                public boolean test(Author author) {
                    return author.getAge() < 18;    //获取年龄小于18的对象
                }
            })
            .forEach(new Consumer<Author>() {
                @Override
                public void accept(Author author) {
                    System.out.println(author.getName());   //打印对象的名字
                }
            });
}

在这里插入图片描述

常用操作

创建流

单例集合集合对象.stream()

List<Integer> list = new ArrayList<>();
Stream<Integer> stream = list.stream();

数组Arrays.stream(数组)Stream.of(数组) 来创建

Integer[] arr = {1,2,3,4};
Stream<Integer> stream1 = Arrays.stream(arr);
Stream<Integer> stream2 = Stream.of(arr);

双例集合:转换成单例集合后再创建

Map<String, String> map = new HashMap<>();
Stream<Map.Entry<String, String>> stream3 = map.entrySet().stream();

中间操作

1、filter
对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

public static void test() {
    List<Author> authors = getAuthors();
    authors.stream()
            .filter(author -> author.getAge() > 18) //中间操作
            .forEach(author -> System.out.println(author)); //终结操作
}

2、map
可以把流中的元素进行计算或转换。

转换:

public static void test() {
    List<Author> authors = getAuthors();
    authors.stream()
            .map(new Function<Author, String>() {
                //泛型中,第一个参数为方法的参数类型(流中的类型),第二个参数为方法的返回值类型
                @Override
                public String apply(Author author) {
                    return author.getName();
                }
            })
            .forEach(new Consumer<String>() {
                @Override
                public void accept(String name) {
                    System.out.println(name);
                }
            });
}

简化

public static void test() {
    List<Author> authors = getAuthors();
    //泛型中,第一个参数为方法的参数类型,第二个参数为方法的返回值类型
    authors.stream()
            .map(author -> author.getName())
            .forEach(name -> System.out.println(name));
}

在这里插入图片描述

计算:

public static void test() {
    List<Author> authors = getAuthors();
    //泛型中,第一个参数为方法的参数类型,第二个参数为方法的返回值类型
    authors.stream()
            .map(author -> author.getAge())
            .map(age -> age+10)
            .forEach(age -> System.out.println(age));
}

在这里插入图片描述

3、distinct
去除流中的重复元素。

注意:distinct方法是依赖Object的equals方法来判断是否是相同对象,所以需要重写equals方法。

4、sorted
对流中的元素进行排序。

方式一:调用sorted()空参方法
在比较的实体类上要实现Comparable接口,不然会报类型不匹配的异常。
在这里插入图片描述

public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .distinct()
            .sorted()
            .forEach(author -> System.out.println(author.getAge()));
}

方式二:在sorted方法中实现Comparator接口

public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .distinct()
            .sorted(new Comparator<Author>() {
                @Override
                public int compare(Author o1, Author o2) {
                    return o1.getAge()-o2.getAge();
                }
            })
            .forEach(author -> System.out.println(author.getAge()));
}

优化

public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .distinct()
            .sorted((o1, o2) -> o1.getAge()-o2.getAge())
            .forEach(author -> System.out.println(author.getAge()));
}

5、limit
可以设置流的最大长度,超出的部分将被抛弃。

//对流中的元素按照年龄进行降序排序,并且要求不能有重复元素,打印其中年龄最大的两个作家。
public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .distinct()
            .sorted((o1, o2) -> o2.getAge()-o1.getAge())
            .limit(2)
            .forEach(author -> System.out.println(author.getName()));
}

6、skip
跳过流中的前n个元素,返回剩下的元素。

7、flatMap
map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。

案例1:打印所有书籍的名字,要求对重复的元素进行去重。
map方式:Author对象的books属性是集合类型,使用原来map转换对象,要使用嵌套循环进行打印。

public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .map(author -> author.getBooks())
            .forEach(books -> {
                for (Book book : books) {
                    System.out.println(book.getName());
                }
            });
}

flatMap方式:

public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .forEach(book -> System.out.println(book.getName()));
}

案例二:打印现有数据的所有分类,要求对分类进行去重。不能出现这种格式:哲学,爱情,要将它们拆开输出。

public static void test3() {
    List<Author> authors = getAuthors();
    authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
            .distinct()
            .forEach(category -> System.out.println(category));
}

在这里插入图片描述

终结操作

1、forEach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。

2、count
获取当前流中元素的个数。

//打印这些作家的所出书籍的数量
public static void test4() {
    List<Author> authors = getAuthors();
    long count = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .count();
    System.out.println(count);
}

3、max&min
获取流中的最值

//分别获取这些作家所出书籍的最高分和最低分
public static void test4() {
    List<Author> authors = getAuthors();
    Optional<Integer> max = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .map(book -> book.getScore())
            .max((o1, o2) -> o1 - o2);
    Optional<Integer> min = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .map(book -> book.getScore())
            .min(((o1, o2) -> o1 - o2));
    System.out.println(max.get());
    System.out.println(min.get());
}

4、collect
把当前流转换成一个集合。

list集合

//获取一个存放所有作者名字的list集合
public static void test5() {
    List<Author> authors = getAuthors();
    List<String> nameList = authors.stream()
            .map(author -> author.getName())
            .collect(Collectors.toList());
    System.out.println(nameList);
}

set集合

//获取一个存放所有作者名字的set集合
public static void test5() {
    List<Author> authors = getAuthors();
    Set<String> nameList = authors.stream()
            .map(author -> author.getName())
            .collect(Collectors.toSet());
    System.out.println(nameList);
}

map集合

//获取一个Map集合,map的key为作者名,value为List<Book>
public static void test5() {
    List<Author> authors = getAuthors();
    Map<String, List<Book>> map = authors.stream()
            .distinct()
            .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
    System.out.println(map);
}

5、查找与匹配

(1)anyMatch:判断是否有任意符合匹配条件的元素,结果为boolean类型。

//判断是否有作家年龄在18以上
public static void test6() {
    List<Author> authors = getAuthors();
    boolean flag = authors.stream()
            .anyMatch(author -> author.getAge() > 18);
    System.out.println(flag);
}

(2)allMatch:判断是否都符合条件,如果都符合返回true,否则返回false

//判断是否所有作家年龄在18以上
public static void test6() {
    List<Author> authors = getAuthors();
    boolean flag = authors.stream()
            .allMatch(author -> author.getAge() > 18);
    System.out.println(flag);
}

(3)noneMatch:判断流中的元素是否都不符合匹配条件,如果都不符合结果为true,否则结果为false。

(4)findAny:获取流中的任意一个元素。该方法没有办法保证获取到的一定是流中的第一个元素。

//获取任意一个年龄大于18的作家,如果存在就输出他的名字
public static void test7() {
    List<Author> authors = getAuthors();
    Optional<Author> any = authors.stream()
            .filter(author -> author.getAge() > 18)
            .findAny();
    //如果这个Optional中有元素,则执行方法,没有就不执行
    any.ifPresent(author -> System.out.println(author.getName()));
}

(5)findFirst:获取流中的第一个元素。

//获取一个年龄最小的作家,并输出他的姓名
public static void test7() {
    List<Author> authors = getAuthors();
    Optional<Author> any = authors.stream()
            .sorted((o1, o2) -> o1.getAge()-o2.getAge())
            .findFirst();
    any.ifPresent(author -> System.out.println(author.getName()));
}

(6)reduce归并
对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)

reduce的作用是把stream中的元素给组合起来。我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。

它内部的计算方式如下:

T result = identity;
for (T element : this stream)
	result = accumulator.apply(result, element)
return result;

其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。

案例1:使用reduce求所有作者年龄的和

public static void test8() {
    List<Author> authors = getAuthors();
    Integer sum = authors.stream()
            .distinct()
            .map(author -> author.getAge())
            //初始值为0,后面 result+=element,最后 return result
            .reduce(0, (result, element) -> result + element);
    System.out.println(sum);
}

案例2:使用reduce求所有作者中年龄的最大值

public static void test8() {
    List<Author> authors = getAuthors();
    Integer max = authors.stream()
            .map(author -> author.getAge())
            .reduce(Integer.MIN_VALUE, (result, element) -> result > element ? result : element);
    System.out.println(max);
}

reduce有个重载形式,内部代码如下:

boolean foundAny = false;
T result = null;
for (T element : this stream) {
	if(!foundAny) {
		foundAny = true;
		result = element;
	} else {
		result = accumulator.apply(result, element);
	}
}
return foundAny ? Optional.of(result) : Optional.empty();

利用这个重载形式,求作者年龄的最大值,不用传递初始值了。

public static void test8() {
    List<Author> authors = getAuthors();
    Optional<Integer> max = authors.stream()
            .map(author -> author.getAge())
            .reduce((result, element) -> result > element ? result : element);
    System.out.println(max.get());
}

注意事项

惰性求值:如果没有终结操作,中间操作是不会得到执行的。

流是一次性的:一旦一个流对象经过一个终结操作后,这个流就不能再被使用了,只能重新创建流对象再使用。

不会影响原数据:我们在流中可以对数据做很多处理,但正常情况下是不会影响原来集合中的元素的。

Optional

我们在编写代码的时候出现最多的就是空指针异常,所以在很多情况下我们需要做各种非空的判断。尤其是对象中的属性还是一个对象的情况下,这种判断会更多。

Author author = getAuthor();
if(author != null) {
	sout(author.getName());
}

过多的判断语句会让我们的代码显得臃肿,所以在JDK8中引入了Optional,养成使用Optional的习惯后,你可以写出更优雅的代码来避免空指针异常。

创建对象

Optional就好像是包装类,可以把我们的具体数据封装到Optional对象内部,然后我们去使用Optional中封装好的方法 操作封装进去的数据,就可以非常优雅的避免空指针异常。

我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象,无论传入的参数是否为null都不会出现问题。

public static void main(String[] args) {
    Optional<Author> optionalAuthor = getOptionalAuthors();
    optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
}

private static Optional<Author> getOptionalAuthors() {
    Author author = new Author(1L, "蒙多", 17, "一个祖安人", null);
    return Optional.ofNullable(author);
}

如果你可以确定一个对象不为空,则可以使用Optional的静态方法of来把数据封装成Optional对象。

Author author = new Author();
Optional<Author> optionalAuthor = Optional.of(author);

如果传入of()方法的对象为空,也会报空指针异常。

观察ofNullable()方法的源码也可以发现,它是调用了of()方法的,只是对对象做了非空的判断。
在这里插入图片描述

private static Optional<Author> getOptionalAuthor2() {
    Author author = new Author(1L, "蒙多", 17, "一个祖安人", null);
    return author == null ? Optional.empty() : Optional.of(author);
}

安全消费值

我们获取到一个Optional对象后,肯定需要对其中的数据进行使用,这时候我们可以使用其ifPresent方法来消费其中的值。

这个方法会判断其内部封装的数据是否为空,不为空时才会执行具体的消费代码,这样使用起来就更加安全了。

安全获取值

如果我们期望安全获取值,不推荐使用get()方法获取,而是用如下方法:

  • orElseGet
    获取数据并且设置数据为空时的默认值。如果数据不为空则获取到该数据,如果为空则返回传入的参数来创建对象。
    public static void main(String[] args) {
        Optional<Author> optionalAuthor = getOptionalAuthors();
        Author author = optionalAuthor.orElseGet(() -> new Author(2L, "蒙多2", 17, "一个祖安人", null));
        System.out.println(author.getName());
    }
    
    private static Optional<Author> getOptionalAuthors() {
        Author author = new Author(1L, "蒙多", 17, "一个祖安人", null);
        return Optional.ofNullable(author);
    }
    
  • orElseThrow
    获取数据,如果数据不为空则获取数据,如果为空则根据传入的参数来创建异常抛出。
    public static void main(String[] args) {
        Optional<Author> optionalAuthor = getOptionalAuthors();
        Author author = optionalAuthor.orElseThrow(() -> new RuntimeException("数据为null"));
        System.out.println(author);
    }
    

过滤

我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但不符合判断条件,也会变成一个无数据的Optional对象。

private static void getOptionalAuthor3() {
    Optional<Author> authorOptional = getOptionalAuthors();
    authorOptional
            .filter(author -> author.getAge() < 18)	//过滤
            .ifPresent(author -> System.out.println(author.getName()));	//消费
}

判断

我们可以使用isPresent方法进行判断是否存在数据的判断。如果为空,返回值为false,如果不为空,返回值为true。
但这种方式不能体现Optional的好处,更推荐使用ifPresent方法。

public static void testIsPresent() {
    Optional<Author> authorOptional = getOptionalAuthors();
    if (authorOptional.isPresent()) {
        System.out.println(authorOptional.get().getName());
    }
}

数据转换

Optional还提供了map可以让我们的数据进行转换,并且转换得到的数据也还是Optional包装好的,保证了我们的使用安全。

public static void testMap() {
    Optional<Author> optionalAuthors = getOptionalAuthors();
    Optional<List<Book>> optionalBooks = optionalAuthors.map(author -> author.getBooks());
    optionalBooks.ifPresent(books -> System.out.println(books));
}

函数式接口

只有一个抽象方法的接口我们称为函数接口。

JDK的函数式接口都加上了@FunctionalInterface注解进行标识。但是无论是否加上该注解,只要接口中只有一个抽象方法,就是函数式接口。

常见函数式接口

  • Consumer 消费接口
    根据其中抽象方法的参数列表和返回值类型可以知道,我们可以在方法中对传入的参数进行消费。
    在这里插入图片描述
  • Function 计算转换接口
    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回。
    在这里插入图片描述
  • Predicate 判断接口
    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果。
    在这里插入图片描述
  • Supplier 生产型接口
    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回。
    在这里插入图片描述

常用的默认方法

  • and
    我们在使用Predicate接口的时候可能需要进行判断条件的拼接,而and方法相当于是使用&&来拼接两个判断条件。
    例1:

    //打印作家中年龄大于17并且姓名的长度大于1的作家
    public static void test9() {
        List<Author> authors = getAuthors();
        Stream<Author> authorStream = authors.stream();
        authorStream.filter(new Predicate<Author>() {
            @Override
            public boolean test(Author author) {
                return author.getAge() > 17;
            }
        }.and(new Predicate<Author>() {
            @Override
            public boolean test(Author author) {
                return author.getName().length() > 1;
            }
        })).forEach(author -> System.out.println(author));
    }
    

    例2:

    public static void main(String[] args) {
        printNum2(value -> value % 2 == 0, value -> value > 4);
    }
    public static void printNum2(IntPredicate predicate, IntPredicate predicate2) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
            if (predicate.and(predicate2).test(i)) {
                System.out.println(i);
            }
        }
    }
    
  • or
    我们在使用Predicate接口的时候可能需要进行判断条件的拼接。而or方法相当于是使用 || 来拼接两个判断条件。

    //年龄大于17或者名字的长度大于4
    private static void testOr() {
        List<Author> authors = getAuthors();
        authors.stream()
                .filter(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getAge() > 17;
                    }
                }.or(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getName().length() > 4;
                    }
                }))
                .forEach(author -> System.out.println(author));
    }
    
  • negate
    Predicate接口中的方法。negate方法相当于是在判断添加前面加了个 !,表示取反

    //获取作家的年龄不大于17
    private static void testNegate() {
        List<Author> authors = getAuthors();
        authors.stream()
                .filter(new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getAge() > 17;
                    }
                }.negate())
                .forEach(author -> System.out.println(author.getAge()));
    }
    

这些方法主要是在自定义函数式编程使用。

方法引用

我们在使用lambda时,如果方法体中只有一个方法的调用的话,我们可以用方法引用进一步简化代码。

推荐用法:我们在使用lambda时不需要考虑什么时候用方法引用,方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码,并且在方法的调用时使用快捷键尝试是否能转换成方法引用即可。

基本格式类名或对象名::方法名

引用类的静态方法

类名::方法名

使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。

List<Author> authors = getAuthors();
authors.stream()
        .map(author -> author.getAge())
        .map(new Function<Integer, String>() {
            @Override
            public String apply(Integer age) {
                return String.valueOf(age);
            }
        });

优化

List<Author> authors = getAuthors();
authors.stream()
        .map(author -> author.getAge())
        .map(String::valueOf);

引用对象的实例方法

格式:对象名::方法名

使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法。

List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
        .map(author -> author.getName())
        .forEach(sb::append);
List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
        .map(author -> author.getName())
        .forEach(new Consumer<String>() {
            @Override
            public void accept(String name) {
                sb.append(name);
            }
        });

引用类的实例方法

格式:类名::方法名

使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法,并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入这个成员方法中,这个时候我们就可以引用类的实例方法。

public class MethodDemo {
    interface UserString {
        String use(String str, int start, int length);
    }
    
    public static String subAuthorName(String str, UserString userString) {
        int start = 0;
        int length = 1;
        return userString.use(str, start, length);
    }

    public static void main(String[] args) {
        subAuthorName("hxp", new UserString() {
            @Override
            public String use(String str, int start, int length) {
                return str.substring(start, length);
            }
        });
    }
}
public class MethodDemo {
    interface UserString {
        String use(String str, int start, int length);
    }

    public static String subAuthorName(String str, UserString userString) {
        int start = 0;
        int length = 1;
        return userString.use(str, start, length);
    }

    public static void main(String[] args) {
        subAuthorName("hxp", String::substring);
    }
}

构造器引用

如果方法体中的一行代码是构造器的话就可以使用构造器引用。

格式:类名::new

使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。

List<Author> authors = getAuthors();
authors.stream()
        .map(author -> author.getName())
        .map(name -> new StringBuilder(name))
        .map(sb -> sb.append("hxp"))
        .forEach(str -> System.out.println(str));

优化

List<Author> authors = getAuthors();
authors.stream()
        .map(author -> author.getName())
        .map(StringBuilder::new)
        .map(sb -> sb.append("hxp"))
        .forEach(str -> System.out.println(str));

高级用法

基本数据类型优化

我们之前用到的很多Stream的方法由于都使用了泛型,所以涉及到的参数和返回值都是引用数据类型。

即使我们操作的数字类型,但实际使用的是它们的包装类。

自动装箱和拆箱是需要消耗时间的,在数据量大的情况下,不断重复装箱拆箱的时候,就不能无视这个时间的损耗了。

Stream提供了很多专门针对基本数据类型的方法,对这部分的时间消耗进行优化。

优化前:匿名内部类中转换的是包装类型,也就意味着后面的操作都要进行装箱和拆箱。

List<Author> authors = getAuthors();
authors.stream()
        .map(new Function<Author, Integer>() {
            @Override
            public Integer apply(Author author) {
                return author.getAge();
            }
        })
        .map(age -> age + 10)
        .filter(age -> age > 18)
        .map(age -> age+2)
        .forEach(System.out::println);

优化后,匿名内部类中转换的是基本类型,也就意味着后面操作的是基本类型。

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

并行流

当流中有大量元素时,我们可以使用并行流去提高操作的效率。

并行流就是把任务分配给多个线程去执行。如果我们自己使用代码去实现会很复杂,并且要求你对并发编程有足够的理解和认识。

如果使用Stream的话,我们只需要修改一个方法的调用就可以使用并行流帮我们实现,从而提高效率。

parallel方法可以把串行流转换成并行流。

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
Integer sum = stream.parallel()
        .peek(new Consumer<Integer>() {
            @Override
            public void accept(Integer num) {
                System.out.println(num + "->" + Thread.currentThread().getName());
            }
        })
        .filter(num -> num > 5)
        .reduce((result, element) -> result + element)
        .get();
System.out.println(sum);

也可以通过parallelStream直接获取并行流对象。

List<Author> authors = getAuthors();
authors.parallelStream()
        .map(author -> author.getName())
        .map(StringBuilder::new)
        .map(sb -> sb.append("hxp"))
        .forEach(str -> System.out.println(str));
  • 7
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值