函数式编程-Stream流学习
一、Lambda表达式
基本格式:(参数列表)->{代码}
省略规则:
-
-
参数类型可以省略
-
方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
-
方法只有一个参数时小括号可以省略
-
以上这些规则都记不住也可以省略不记
-
二、Stream流
-
filter
- 可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
打印所有姓名长度大于1的作家的姓名
List<Author> authors = getAuthors(); authors.stream() .filter(author -> author.getName().length()>1) .forEach(author -> System.out.println(author.getName()));
-
forEach
- 对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
输出所有作家的名字
// 输出所有作家的名字 List<Author> authors = getAuthors(); authors.stream() .map(author -> author.getName()) .distinct() .forEach(name-> System.out.println(name));
-
collect
- 把当前流转换成一个集合。
获取一个存放所有作者名字的List集合。
// 获取一个存放所有作者名字的List集合。 List<Author> authors = getAuthors(); List<String> nameList = authors.stream() .map(author -> author.getName()) .collect(Collectors.toList()); System.out.println(nameList);
-
map
- 可以把对流中的元素进行计算或转换。
打印所有作家的姓名
// 打印所有作家的姓名 List<Author> authors = getAuthors(); // authors.stream() // .map(author -> author.getName()) // .forEach(s -> System.out.println(s)); authors.stream() .map(author -> author.getAge()) .map(age->age+10) .forEach(age-> System.out.println(age));
-
distinct
- 可以去除流中的重复元素。
打印所有作家的姓名,并且要求其中不能有重复元素。
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.forEach(author -> System.out.println(author.getName()));
-
sorted
- 可以对流中的元素进行排序
对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
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() .limit(2) .forEach(author -> System.out.println(author.getName()));
-
skip
- 跳过流中的前n个元素,返回剩下的元素
打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
// 打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。 List<Author> authors = getAuthors(); authors.stream() .distinct() .sorted() .skip(1) .forEach(author -> System.out.println(author.getName()));
-
flatMap
- map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素
打印所有书籍的名字。要求对重复的元素进行去重。
// 打印所有书籍的名字。要求对重复的元素进行去重。 List<Author> authors = getAuthors(); authors.stream() .flatMap(author -> author.getBooks().stream()) .distinct() .forEach(book -> System.out.println(book.getName()))

浙公网安备 33010602011771号