函数式编程从入门到精通

1.概述

1.1为什么学?

* 能够看懂公司里的代码
* 大数量下处理集合效率高
* 代码可读性高
* 消灭嵌套地狱
    //查询未成年作家评分在70分以上的书籍,由于流的影响所以作家和书籍可能会重复出现,所以要去重public void test1() {List<Book> bookList = new ArrayList<>();List<Author> authorList = new ArrayList<>();Set<Book> uniqueBookValues = new HashSet<>();Set<Author> uniqueAuthorValues = new HashSet<>();for (Author author : authorList) {// 这里如果重复就不会添加成功if (uniqueAuthorValues.add(author)) {if (author.getAge() < 18) {List<Book> books = author.getBookList();for (Book book : books) {if (book.getScore() > 70D) {// 如果之前有这本书就不会再次添加if (uniqueBookValues.add(book)) {bookList.add(book);}}}}}}System.out.println(bookList);// authorList.add(new Author());// 函数式写法List<Book> collect = authorList.stream().distinct().filter(author -> author.getAge() < 18).map(author -> author.getBookList()).flatMap(Collection::stream).filter(book -> book.getScore() > 70).distinct().collect(Collectors.toList());System.out.println(collect);}

1.2函数式编程思想

1.2.1概念

面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。

1.2.2优点

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

2. Lambda表达式


2.1概述

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

不关注类名和方法名,只关注参数(数据)和方法体(操作

2.2核心原则

可推导可省略

2.3基本格式

(参数列表)->{代码}

        //我们在创建线程并启动时可以使用匿名内部类的写法:new Thread(new Runnable() {@Overridepublic void run() {System.out.println("这是匿名内部类写法");}}).start();//可以使用Lambda的格式对其进行修改。修改后如下:new Thread(() -> {System.out.println("这是lambda写法");}).start();

2.4省略规则

  • 参数类型可以省略
  • 方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
  • 方法只有一个参数时小括号可以省略
  • 以上这些规则都记不住也可以省略不记

3.Stream流

3.1概述

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

3.2案例准备

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author {
//id
private Long id;
//姓名
private String name;
//年龄
private Integer age;
//简介
private String intro;
//作品
private List<Book> books;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Book {
//id
private Long id;
//书名
private String name;
//分类
private String category;
//评分
private Integer score;
//简介
private String intro;
}
    private static List<Author> getAuthors() {//数据初始化Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);Author author2 = new Author(2L, "亚拉索", 15, "狂风也追逐不上他的思考速度", null);Author author3 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);Author author4 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);//书籍列表List<Book> books1 = new ArrayList<>();List<Book> books2 = new ArrayList<>();List<Book> books3 = new ArrayList<>();books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败中明悟真理"));books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));books2.add(new Book(4L, "吹或不吹", "爱情,个人传记", 56, "一个哲学家的恋爱观注定很难把他所在的时代理解"));books3.add(new Book(5L, "你的剑就是我的剑", "爱情", 56, "天无法想象一个武者能对他的伴侣这么的宽容"));books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));author.setBooks(books1);author2.setBooks(books2);author3.setBooks(books3);author4.setBooks(books3);List<Author> authorList = new ArrayList<>(Arrays.asList(author, author2, author3, author4));return authorList;}

3.3快速入门

3.3.1需求

我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重。

3.3.2实现

List<Author> authors = getAuthors();authors.stream() //把集合转换成流.distinct() //去重.filter(author -> author.getAge() < 18) //筛选年龄小于18的.forEach(author -> System.out.println(author.getName())); //遍历打印名字

3.4常用操作

3.4.1创建流

单列集合:集合对象.stream()

List<Author>authors = getAuthors();
Stream<Author> stream = authors.stream();

数组:Arrays.stream(数组)或者使用Stream.of来创建

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

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

Map<String,Integer> map = new HashMap<>();
map.put("蜡笔小新",19);S
map.put("黑子",17);
map.put("日向翔阳",16);
Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream()

3.4.2中间操作

filter

可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
例如:打印所有姓名长度大于1的作家的姓名

        List<Author> authors = getAuthors();authors.stream().filter(author -> author.getName().length()>1).forEach(author -> System.out.println(author.getName()));
map

可以把对流中的元素进行计算或转换。
例如:打印所有作家的姓名

        List<Author> authors = getAuthors();authors.stream().map(author ->author.getName()).forEach(name->System.out.println(name));
        List<Author> authors = getAuthors();authors.stream().map(author ->author.getAge())//转换.map(age->age+10)//计算.forEach(age->System.out.println(age));
distinct

可以去除流中的重复元素。
例如:打印所有作家的姓名,并且要求其中不能有重复元素。
注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重新equals方法。

        List<Author> authors = getAuthors();authors.stream().map(author -> author.getName()).distinct().forEach(name -> System.out.println(name));
sorted

可以对流中的元素进行排序。
例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。

注意:如果调用空参的sorted()方法,需要流中的元素是实现Comparable接口

        List<Author>authors = getAuthors();//对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素authors.stream().distinct().sorted().forEach(author -> System.out.println(author.getAge()));
        List<Author>authors = getAuthors();//对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素authors.stream().distinct().sorted((o1, o2) -> o2.getAge()-o1.getAge()).forEach(author -> System.out.println(author.getAge()));
limit

可以设置流的最大长度,超出的部分将被抛弃。
例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。

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

跳过流中的前n个元素,返回剩下的元素
例如:打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。

        List<Author>authors = getAuthors();//打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序authors.stream().distinct().sorted((o1, o2) -> o2.getAge()-o1.getAge()).skip(1).forEach(author -> System.out.println(author.getName()));
flatMap

map只能把一个对象转换成另一个对象来作为流中的元素。而flatMaap可以把一个对象转换成多个对象作为流中的元素。
例一:打印所有书籍的名字。要求对重复的元素进行去重。

        List<Author>authors = getAuthors();//打印所有书籍的名字。要求对重复的元素进行去重authors.stream().flatMap(author -> author.getBooks().stream()).distinct().forEach(book -> System.out.println(book.getName()));

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

        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));
分组

将流中的元素根据某个属性或规则进行分类,并返回一个映射,其中键是分组依据的值,值是每个分组中元素的集合。

基本用法

例如:将作家按照名字分组,并打印出每个名字及其对应的作家。

Map<String, List<Author>> groupByName = getAuthors().stream().collect(Collectors.groupingBy(new Function<Author, String>() {@Overridepublic String apply(Author author) {return author.getName();}}));
groupByName.forEach((name, authors) -> {System.out.println(name);authors.forEach(System.out::println);
});
多级分组

有时,我们可能需要对数据进行多级分组。

例如:首先按照年龄分组,然后按照姓名分组

Map<Integer, Map<String, List<Author>>> groupByAgeThenName = getAuthors().stream().collect(Collectors.groupingBy(author -> author.getAge(), Collectors.groupingBy(author -> author.getName())));
groupByAgeThenName.forEach(new BiConsumer<Integer, Map<String, List<Author>>>() {@Overridepublic void accept(Integer integer, Map<String, List<Author>> stringListMap) {System.out.println("年龄:" + integer);stringListMap.forEach(new BiConsumer<String, List<Author>>() {@Overridepublic void accept(String name, List<Author> authors) {System.out.println("姓名:" + name);authors.forEach(System.out::println);}});}
});
分组聚合

分组操作可以与聚合操作结合使用

例如:计算每个名字的作家平均年龄

Map<String, Double> averageAgeByName = getAuthors().stream().collect(Collectors.groupingBy(author -> author.getName(), Collectors.averagingInt(author -> author.getAge())));
averageAgeByName.forEach((name, age) -> System.out.println("作者:" + name + ",平均年龄:" + age));
分组排序

分组操作还可以与排序结合使用

例如:按照年龄排序后分组

Map<Integer, List<Author>> sortedGroupByAge = getAuthors().stream().sorted(Comparator.comparing(Author::getAge)).collect(Collectors.groupingBy(Author::getAge,LinkedHashMap::new,  // 保持插入顺序Collectors.toList()));
System.out.println(sortedGroupByAge);
sortedGroupByAge.forEach((age, authors) -> {System.out.println(age);authors.forEach(author -> System.out.println(author.getName()));
});

3.4.3终结操作

forEach

对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
例子:输出所有作家的名字

        List<Author>authors = getAuthors();//输出所有作家的名字authors.stream().distinct().map(author -> author.getName()).forEach(name -> System.out.println(name));
count

可以用来获取当前流中元素的个数。
例子:打印这些作家的所出书籍的数目,注意删除重复元素。

        List<Author> authors = getAuthors();//打印这些作家的所出书籍的数目,注意删除重复元素long count = authors.stream().flatMap(author -> author.getBooks().stream()).distinct().count();System.out.println(count);
max&min

可以用来获取流中的最值。
例子:分别获取这些作家的所出书籍的最高分和最低分并打印。

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

把当前流转换成一个集合。
例子:

获取一个存放所有作者名字的List集合。

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

获取一个所有书名的Set集合。

        List<Author> authors = getAuthors();//获取一个所有书名的Set集合Set<String> bookNameSet = authors.stream().flatMap(author -> author.getBooks().stream()).map(book -> book.getName()).collect(Collectors.toSet());System.out.println(bookNameSet);

获取一个Map集合,map的key为作者名,value为List<Book>

        List<Author> authors = getAuthors();//获取一个Map集合,map的key为作者名,value为List<Book>Map<String, List<Book>> map = authors.stream().distinct().collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));System.out.println(map);
查找与匹配
anyMatch

可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
例子:判断是否有年龄在29以上的作家

        List<Author> authors = getAuthors();boolean flag = authors.stream().anyMatch(author -> author.getAge() > 29);System.out.println(flag);

allMatch

可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
例子:判断是否所有的作家都是成年人

        List<Author> authors = getAuthors();boolean flag = authors.stream().allMatch(author -> author.getAge() > 18);System.out.println(flag);

noneMatch

可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false
例子:判断作家是否都没有超过100岁的。

        List<Author> authors = getAuthors();boolean flag = authors.stream().noneMatch(author -> author.getAge() > 100);System.out.println(flag);
findAny

获取流中的任意一个元素。该方法没有办法保证获取的一定是流中中的第一个元素。
例子:获取任意一个年龄大于18的作家,如果存在就输出他的名字

        List<Author> authors = getAuthors();Optional<Author> optionalAuthor = authors.stream().filter(author -> author.getAge() > 18).findAny();optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
findFirst

获取流中的第一个元素。
例子:获取一个年龄最小的作家,并输出他的姓名。

        List<Author> authors = getAuthors();Optional<Author> first = authors.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).findFirst();first.ifPresent(author -> System.out.println(author.getName()));
reduce归并

对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)
reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。
reduce两个参数的重载形式内部的计算方式如下:

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

其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
例子:
使用reduce求所有作者年龄的和

        List<Author> authors = getAuthors();Integer sum = authors.stream().distinct().map(author -> author.getAge()).reduce(0, (result, element) -> result + element);System.out.println(sum);

使用reduce求所有作者中年龄的最大值

        Integer MaxAge = authors.stream().distinct().map(author -> author.getAge()).reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);System.out.println(MaxAge);

使用reduce求所有作者中年龄的最小值

        List<Author> authors = getAuthors();Integer MinAge = authors.stream().distinct().map(author -> author.getAge()).reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);System.out.println(MinAge);

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();

如果用一个参数的重载方法去求最小值代码如下:

        List<Author> authors = getAuthors();Optional<Integer> MinAge = authors.stream().distinct().map(author -> author.getAge()).reduce(new BinaryOperator<Integer>() {@Overridepublic Integer apply(Integer result, Integer element) {return result > element ? element : result;}});MinAge.ifPresent(age -> System.out.println(age));

3.5注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)

4. Optional

4.1概述

我们在编写代码的时候出现最多的就是空指针异常。所以在很多情清况下我们需要做各种非空的判断。
例如:

Author author = getAuthor();
if(author!=null) {System.out.println(author.getName());
}

尤其是对象中的属性还是一个对象的情况下。这种判断会更多。

而过多的判断语句会让我们的代码显得臃肿不堪。

所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。

并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。

4.2使用


4.2.1创建对象

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

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

Author author = getAuthor();
Optional<Author> authorOptional = Optional.ofNullable(author);

你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下geAuthor方法,让其的返回值就是封装好的Optional的话,我们在使用时就会方便很多。

而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。

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

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

但是一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)

如果一个方法的返回值类型是Optional类型。而如果我们经判断发现其某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional静态方法empty来进行封装Optional.empty()

4.2.2安全消费值

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

这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。
例如,以下写法就优雅的避免了空指针异常。

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
authorOptional.ifPresent(author -> System.out.println(author.getName()));

4.2.4安全获取值

如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。

orElseGet

获取数据并且设置数据为空时的默认值。如果数据不为空就能获!取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
Author author = authorOptional.orElseGet(() ->new Author());
orElseThrow

获取数据,如果数据不为空就能获取到该数据。如果数据为空则根据你传入的参数来创建异常抛出

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
try{Author author = authorOptional.orElseThrow((Supplier<Throwable>)() -> new RuntimeException("author为空"));System.out.println(author.getName());
} catch (Throwable throwable) {throwable.printStackTrace();
}

4.2.5过滤

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

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
authorOptional.filter(author -> author.getAge() > 100).ifPresent(author -> System.out.println(author.getName()));

4.2.6判断

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

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
if(authorOptional.isPresent()) {System.out.println(authorOptional.get().getName());
}

4.2.7数据转换

Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。
例如:我们想获取作家的书籍集合。

Optional<Author> authorOptional = Optional.ofNullable (getAuthor());
Optional<List<Book>> books = authorOptional.map((author -> author.getBooks()));
books.ifPresent(new Consumer<List<Book>>() {@Overridepublic void accept(List<Book> books) {books.forEach(book -> System.out.println(book.getName()));}
});

5.函数式接口

5.1概述

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

5.2常见函数式接口

Consumer消费接口

根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。

Function计算转换接口

根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回

5.3 常用的默认方法

and

我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件
例如:打印作家中年龄大于17并且姓名的长度大于1的作家。

List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.filter(new Predicate<Author>() {@Overridepublic boolean test(Author author) {return author.getAge() > 17;}
}.and(new Predicate<Author>() {@Overridepublic boolean test(Author author) {return author.getName().length() > 1;}
})).forEach(author -> System.out.println(author));
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.filter(author -> author.getAge() > 17 && author.getName().length() > 1).forEach(author -> System.out.println(author));

or

我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用|来拼接两个判断条件。
例如:打印作家中年龄大于17或者姓名的长度小于2的作家。

List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.filter(new Predicate<Author>() {@Overridepublic boolean test(Author author) {return author.getAge() > 17;}
}.or(new Predicate<Author>() {@Overridepublic boolean test(Author author) {return author.getName().length() > 2;}
})).forEach(author -> System.out.println(author));

negate

Predicate接口中的方法。negate方法相当于是在判断添加前面加了个!表示取反
例如:打印作家中年龄不大于17的作家。

List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.filter(new Predicate<Author>() {@Overridepublic boolean test(Author author) {return author.getAge() > 17;}}.negate()).forEach(author -> System.out.println(author));

6.方法引用

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

6.1推荐用法

我们在使用lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转传成方法引用即可。
当我们方法引用使用的多了慢慢的也可以直接写出方法引用。

6.2基本格式

类名或者对象名::方法名

6.3语法详解(了解)

6.3.1引用类的静态方法

其实就是引用类的静态方法
格式

类名::方法名

使用前提

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

例如:

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

优化后:

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

6.3.2引用对象的实例方法

格式

对象名::方法名

使用前提

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

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

优化后:

List<Author>authors = getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName()).forEach(sb::append);

6.3.4引用类的实例方法

格式

类名::方法名

使用前提

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

例如:

public class MethodDemo {interface UseString {String use(String str, int start, int length);}public static String subAuthorName(String str, UseString useString) {int start = 0;int length = 1;return useString.use(str, start, length);}public static void main(String[] args) {subAuthorName("hello world", new UseString() {@Overridepublic String use(String str, int start, int length) {return str.substring(start, length);}});}
}

优化后:

public class MethodDemo {interface UseString {String use(String str, int start, int length);}public static String subAuthorName(String str, UseString useString) {int start = 0;int length = 1;return useString.use(str, start, length);}public static void main(String[] args) {subAuthorName("hello world", String::substring);}
}

6.3.5构造器引用

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

类名::new

使用前提

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

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

优化后:

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

7.高级用法

基本数据类型优化

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

即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很小。但是在大量的数居不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。

所以为了让我们能够对这部分的时间消耗进行优化。Stream还还是供了很多专门针对基本数据类型的方法。

例如: mapToint,mapToLong,mapToDouble,flatMapTğlnt,flatMapToDouble等。

List<Author>authors = getAuthors();
authors.stream().map(author ->author.getAge()).map(age ->age + 10).filter(age->age>18).map(age->age+2).forEach(System.out::println);

优化后:

List<Author>authors = getAuthors();
authors.stream().mapToInt(author ->author.getAge()).map(age ->age + 10).filter(age->age>18).map(age->age+2).forEach(System.out::println);

并行流

当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完全。如果我们自己去用代码实现的话其实会非常的复杂,并且要求你对并发编程有足够的理解解和认识。而如果我们使用Stream的话,我们只需要修改一个方去的调用就可以使用并行流来帮我们实现,从而提高效率。

parallel方法可以把串行流转换成并行流。也可以通过parallelStream直接获取并行流对象。

Stream<Integer> stream = Stream.of(1, 2, 3, 44, 5, 6, 7, 8, 9, 10);
Integer sum = stream.parallel().peek(new Consumer<Integer>() {@Overridepublic void accept(Integer num) {System.out.println(num + ":" + Thread.currentThread().getName());}}).filter(num -> num > 5).reduce((x, y) -> x + y).get();
System.out.println(sum);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/919893.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/919893.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Overleaf 中文报错和中文不显示问题的解决方案

Overleaf是一个很方便的在线latex编辑工具。但在最初使用Overleaf的时候&#xff0c;是不是有很多小伙伴会遇到模板中中文报错或者中文不显示的问题呢&#xff1f; 本文将带你一步步解决这个问题~ 中文报错 在点击重新编译按钮后&#xff0c;中文报错问题一般会有如下图红框显示…

前后端联调场景以及可能会遇到的问题

一、异地和在一起办公的方式 首先&#xff0c;在一起办公&#xff08;同局域网&#xff09;的情况&#xff0c;最常用的应该是直接使用后端的局域网 IP 进行联调&#xff0c;因为同一网络内设备可以直接通信。步骤方面&#xff0c;需要后端提供 IP 和端口&#xff0c;前端配置…

【T113自制板卡】1 - 原理图说明

文章目录1、前言2、板卡资源总览3、电源3.1、板卡供电3.2、电源方案4、OTG接口5、调试串口6、用户LED7、FLASH8、按键9、BLE MESH10、Wi-Fi11、MIC12、喇叭接口13、MIPI接口1、前言 这几天跟着小智学长的课程画了一块t113的板子。本文将描述该板卡的硬件说明。 2、板卡资源总…

WiFi有网络但是电脑连不上网是怎么回事?该怎么解决?

有时候&#xff0c;咱们用电脑上网&#xff0c;打开WiFi一看&#xff0c;信号满格&#xff0c;状态栏显示已连接&#xff0c;本来想着可以愉快地看个番、查个资料、玩个游戏了&#xff0c;结果一打开浏览器&#xff0c;直接完犊子了&#xff0c;网页都打不开。这时候再看状态&a…

【golang】制作linux环境+golang的Dockerfile | 如何下载golang镜像源

一、关于如何下载docker images 这里需要大家自行科学上网如果没有话&#xff0c;下面可以使用我自行打包的golang 的docker images 注意科学上网要开启TUN模式二、golang镜像源 1、阿里云公开镜像 如果找不到golang包的小伙伴可以使用我的公开阿里镜像docker pull registry.cn…

Day58 Java面向对象13 instanceof 和 类型转换

Day58 Java面向对象13 instanceof 和 类型转换 1.instanceof关键字 instanceof关键字的作用是判断一个对象是否是某个类或其子类的实例,它返回一个布尔值true/false dog1 instanceof Dog; //返回true dog1 instanceof Animals; //返回true dog1 instanceof Object; //返回…

GEO优化案例:如何通过“知识图谱+权威信号”提升品牌AI信任度

引言&#xff1a; “在AI日益成为用户信息入口的今天&#xff0c;品牌信息能否被AI赋予‘权威’标签&#xff0c;直接决定了其在搜索结果中的可见度和用户采信度。移山科技正是这方面的专家。” 一、行业趋势概览&#xff1a;AI时代的品牌信任与GEO的价值 2025年&#xff0c…

让数据可视化更简单:Embedding Atlas使用指南

Embedding Atlas&#xff1a;交互式的嵌入可视化工具 在大数据时代&#xff0c;如何有效地理解和利用高维数据变得愈发重要。Embedding Atlas 是一款致力于提供大型嵌入&#xff08;embeddings&#xff09;交互式可视化的工具&#xff0c;允许用户对嵌入数据进行可视化、交叉过…

复杂场景鲁棒性突破!陌讯自适应融合算法在厂区越界检测的实战优化​

一、行业痛点&#xff1a;越界检测的复杂场景挑战 工业厂区周界安防中&#xff0c;越界检测极易受环境干扰。据《2024工业智能安防白皮书》统计&#xff08;注1&#xff09;&#xff0c;强逆光、雨雾天气导致传统算法误报率超35%&#xff0c;而密集设备遮挡造成的漏检率高达28…

Huggingface入门实践 Audio-NLP 语音-文字模型调用(一)

吴恩达LLM-Huggingface_哔哩哔哩_bilibili 目录 0. huggingface 根据需求寻找开源模型 1. Whisper模型 语音识别任务 2. blenderbot 聊天机器人 3. 文本翻译模型translator 4. BART 模型摘要器&#xff08;summarizer&#xff09; 5. sentence-transformers 句子相似度 …

Python-Pandas GroupBy 进阶与透视表学习

​​一、数据分组&#xff08;GroupBy&#xff09;​​​​核心概念​​&#xff1a;将数据按指定字段分组&#xff0c;对每组进行聚合、转换或过滤操作。​​1. 分组聚合&#xff08;Aggregation&#xff09;​​将分组数据聚合成单个值&#xff08;如平均值、总和&#xff09…

MQTT 核心概念与协议演进全景解读(二)

MQTT 在物联网中的应用实例智能家居中的设备联动在智能家居系统里&#xff0c;MQTT 协议扮演着至关重要的角色&#xff0c;是实现设备间高效通信与智能联动的核心枢纽。以常见的智能家居场景为例&#xff0c;当清晨的阳光缓缓升起&#xff0c;光线传感器检测到光照强度的变化&a…

燧原科技招大模型训练算法工程师

高级大模型训练算法工程师&#xff08;岗位信息已经经过jobleap.cn授权&#xff0c;可在csdn发布&#xff09;燧原科技 上海职位描述负责大模型在AI芯片预训练和微调等研发和客户支持工作&#xff1b; 参与大模型训练精度分析和性能调优&#xff1b;职位要求985/211大学计算机…

基于Java虚拟线程的高并发作业执行框架设计与性能优化实践指南

基于Java虚拟线程的高并发作业执行框架设计与性能优化实践指南 一、技术背景与应用场景 在分布式系统和微服务架构中&#xff0c;后端常需承载海量异步作业&#xff08;如批量数据处理、定时任务、异步消息消费等&#xff09;&#xff0c;对作业执行框架提出了高并发、高吞吐、…

了解 PostgreSQL 的 MVCC 可见性基本检查规则

1. 引言 根据 Vadim Mikheev 的说法&#xff0c;PostgreSQL 的多版本并发控制&#xff08;MVCC&#xff09;是一种“在多用户环境中提高数据库性能的高级技术”。该技术要求系统中存在同一数据元组的多个“版本”&#xff0c;这些版本由不同时间段内获取的快照进行管理。换句话…

普通烘箱 vs 铠德科技防静电烘箱:深度对比与选择指南

在电子制造、化工、航空航天等精密工业领域&#xff0c;烘箱作为关键工艺设备&#xff0c;其性能直接关系到产品可靠性和生产安全。普通烘箱与防静电烘箱的核心差异在于静电防护能力&#xff0c;而铠德科技作为防静电烘箱领域的专业厂商&#xff0c;其产品通过技术创新重新定义…

达梦数据库巡检常用SQL(一)

达梦数据库巡检常用SQL(一) 数据库基本信息 数据库用户信息 数据库对象检查 数据库基本信息 检查授权信息: SELECT /*+DMDB_CHECK_FLAG*/ LIC_VERSION AS "许可证版本" ,SERIES_NO AS "序列号" ,CHECK_CODE AS "校验码" …

TypeScript的接口 (Interfaces)讲解

把接口&#xff08;Interface&#xff09;想成一份“说明书”或“合同书”。说明书 比如电饭煲的说明书告诉你&#xff1a; 必须有“煮饭”按钮必须有“保温”功能颜色可以是白、黑、红 接口在 TypeScript 里干的就是同样的事&#xff1a;它规定一个对象“长什么样”。 interfa…

Python本源诗话(我DeepSeek)

物理折行新注释&#xff0c;直抒胸臆吾志名。 笔记模板由python脚本于2025-08-23 13:14:28创建&#xff0c;本篇笔记适合喜欢python和诗的coder翻阅。 学习的细节是欢悦的历程 博客的核心价值&#xff1a;在于输出思考与经验&#xff0c;而不仅仅是知识的简单复述。 Python官网…

博士招生 | 美国圣地亚哥州立大学 Yifan Zhang 课题组博士招生,AI 安全领域顶尖平台等你加入!

内容源自“图灵学术博研社”gongzhonghao学校简介圣地亚哥州立大学&#xff08;San Diego State University, SDSU&#xff09;是美国加州南部久负盛名的公立研究型大学。学校坐落于科技产业高度活跃的南加州地区&#xff0c;与本地软件、电信、生物科技、国防及清洁能源等领域…