Lambda表达式
可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作
//匿名内部类的写法
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("你知道吗 我比你想象的 更想在你身边");
}
}).start();
(参数列表)->{代码}
参数类型可以省略
方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
方法只有一个参数时小括号可以省略
//Lambda表达式
new Thread(()->{
System.out.println("你知道吗 我比你想象的 更想在你身边");
}).start();
stream流
stream流调试
debug模式下,点击图中小图标,可以看到stream流方法的每一步
peek检视流中的元素或者修改流中的某个数据项
List<Author> authors = getAuthors();
List<Integer> collect = authors.stream()
.filter(s -> s.getAge() > 30)
//查看某个环节的元素情况
.peek(System.out::println)
// peek还可以用来修改元素内容
.peek(s -> s.setAge(60))
.map(Author::getAge)
.peek(System.out::println)
.collect(Collectors.toList());
System.out.println(collect);
创建流
单列集合: 集合对象.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);
map.put("黑子",17);
map.put("日向翔阳",16);
Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
中间操作
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));
authors.stream()
.map(author -> author.getAge())//获取年龄集合
.map(age->age+10)//每个年龄加10
.forEach(age-> System.out.println(age));
distinct可以去除流中的重复元素
注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法(pojo类中添加@EqualsAndHashCode注解)。
//打印所有作家的姓名,并且要求其中不能有重复元素
List<Author> authors = getAuthors();
authors.stream()
.distinct()//去重
.forEach(author -> System.out.println(author.getName()));
sorted可以对流中的元素进行排序
空参的sorted()方法
//对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
List<Author> authors = getAuthors();
//对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
authors.stream()
.distinct()
.sorted() //注意:如果调用空参的sorted()方法,需要流中的元素(Author)是实现了Comparable接口
.forEach(author -> System.out.println(author.getAge()));
有参的sorted()方法
List<Author> authors = getAuthors();
//对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
authors.stream()
.distinct()
.sorted((o1, o2) -> o2.getAge()-o1.getAge())
.forEach(author -> System.out.println(author.getAge()));
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.sorted(Comparator.comparing(Book::getScore ))
.forEach(book->System.out.println(book));
order by id asc,age desc
// 按id排序,id相同时根据年龄排倒序
List<Author> sorted = authors.stream()
.sorted(Comparator.comparing(Author::getId)
.thenComparing(Author::getAge, Comparator.reverseOrder()))
.collect(Collectors.toList());
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()
.skip(1) //跳过第一个元素
.forEach(author -> System.out.println(author.getName()));
flatMap
map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素
//例一:打印所有书籍的名字。要求对重复的元素进行去重
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream()) //将每个author对象中的book集合汇总到一个流对象中
.distinct()
.forEach(book -> System.out.println(book.getName()));
//例二:打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情
List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())//将每个author对象中的book集合汇总到一个流对象中
.distinct()
.flatMap(book -> Arrays.stream(book.getCategory().split(",")))//获取book中所有的分类category,如果是"哲学,爱情"这种就用","分割,因为是一个数组,所以使用Arrays.stream()获取数组流对象。
.distinct()
.forEach(category-> System.out.println(category));
终结操作
forEach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作
//输出所有作家的名字
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.distinct()
.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();
Book book = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.max(Comparator.comparing(Book::getScore)).get();
//Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?)
System.out.println(book);
collect
把当前流转换成一个集合
//获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toList());
System.out.println(nameList);
//获取一个所有书名的Set集合。
List<Author> authors = getAuthors();
Set<Book> books = authors.stream()
.flatMap(author -> author.getBooks().stream())
.collect(Collectors.toSet());
System.out.println(books);
//获取一个Map集合,map的key为作者名,value为List<Book>
List<Author> authors = getAuthors();
Map<String, List<Book>> map = authors.stream()
.distinct()
//key author -> author.getName()
//value author -> author.getBooks()
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(map);
单列集合转换成双列集合
List -> HashMap<String, Author>
List<Author> authors = getAuthors();
// 使用该方法,可以把流转map或任意集合对象
HashMap<String, Author> map = authors.stream().collect(HashMap::new,
(hashMap, author) -> hashMap.put(author.getName(), author), HashMap::putAll);
System.out.println(map);
Collectors.groupingBy
基础分组功能
List<Author> authors = getAuthors();
// 将不同城市的作家进行分类
Map<String, List<Author>> groupByCourse = authors.stream()
.collect(Collectors.groupingBy(Author::getCity));
Map<String, List<Author>> groupByCourse1 = authors.stream()
.collect(Collectors.groupingBy(Author::getCity, Collectors.toList()));
// 上面的方法中容器类型和值类型都是默认指定的,容器类型为:HashMap,值类型为:ArrayList
// 可以通过下面的方法自定义返回结果、值的类型
Map<String, List<Author>> groupByCourse2 = authors.stream()
.collect(Collectors.groupingBy(Author::getCity, HashMap::new, Collectors.toList()));
自定义键多个字段,映射分组功能
List<Author> authors = getAuthors();
// 组合字段 分组现实每个城市不同区的作家信息
Map<String, List<Author>> combineFiledKey = authors.stream()
.collect(Collectors.groupingBy(author -> author.getCity() + "#" + author.getCnty()));
System.out.println(combineFiledKey);
自定义键,范围
List<Author> authors = getAuthors();
// 根据两级范围 将作家划分及格不及格两类
Map<Boolean, List<Author>> customRangeKey = authors.stream().collect(Collectors.groupingBy(author -> author.getScore() > 60));
// 根据多级范围 根据作家成绩来评分
Map<String, List<Author>> customMultiRangeKey = authors.stream().collect(Collectors.groupingBy(author -> {
if (author.getScore() < 60) {
return "C";
} else if (author.getScore() < 80) {
return "B";
}
return "A";
}));
分组后,对同一分组内的元素进行计算:计数、平均值、求和、最大最小值、范围内数据统计
Collectors.counting:计数
// 计数
Map<String, Long> groupCount = students.stream()
.collect(Collectors.groupingBy(Student::getCourse, Collectors.counting()));
Collectors.summingInt:求和
// 求和
Map<String, Integer> groupSum = students.stream()
.collect(Collectors.groupingBy(Student::getCourse, Collectors.summingInt(Student::getScore)));
Collectors.averagingInt:平均值
// 增加平均值计算
Map<String, Double> groupAverage = students.stream()
.collect(Collectors.groupingBy(Student::getCourse, Collectors.averagingInt(Student::getScore)));
Collectors.minBy:最大最小值
Collectors.minBy方法返回的类型为Optional,可以通过Collectors.collectingAndThen方法实现,并返回校验结果。Collectors.collectingAndThen的作用便是在使用聚合函数之后,对聚合函数的结果进行再加工。
List<Author> authors = getAuthors();
// 同组最小值
Map<String, Optional<Author>> groupMin = authors.stream()
.collect(Collectors.groupingBy(Author::getCity,Collectors.minBy(Comparator.comparing(Author::getScore))));
// 使用Collectors.collectingAndThen方法,处理Optional类型的数据
// orElse(T other):如果optional不为空,则返回optional中的对象;如果为null,则返回 other 这个默认值
Map<String, Author> groupMin2 = authors.stream()
.collect(Collectors.groupingBy(Author::getCity,
Collectors.collectingAndThen(Collectors.minBy(Comparator.comparing(author -> author.getScore())), op ->op.orElse(null))));
// 同组最大值
Map<String, Optional<Author>> groupMax = authors.stream()
.collect(Collectors.groupingBy(Author::getCity,Collectors.maxBy(Comparator.comparing(Author::getScore))));
查找与匹配
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 b = authors.stream()
.noneMatch(author -> author.getAge() > 100);
System.out.println(b);
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();
Author author = authors.stream()
.sorted((o1, o2) -> o1.getAge() - o2.getAge())
.findFirst()
.get();
System.out.println(author);
reduce归并
对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)
reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。
reduce两个参数的重载形式
//使用reduce求所有作者年龄的和
List<Author> authors = getAuthors();
Integer sum = authors.stream()
.distinct()
.map(author -> author.getAge())
//0表示初始值
//result表示累加结果
//element表示每次累加的元素
.reduce(0, (result, element) -> result + element);
System.out.println(sum);
//使用reduce求所有作者中年龄的最大值
List<Author> authors = getAuthors();
Integer max = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
System.out.println(max);
//使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Integer min = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
System.out.println(min);
reduce一个参数的重载形式
//使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Optional<Integer> minOptional = authors.stream()
.map(author -> author.getAge())
//默认第一个元素element为结果result,所以不需要指定最小值
.reduce((result, element) -> result > element ? element : result);
minOptional.ifPresent(age-> System.out.println(age));
字符串拼接
List<Author> authors = getAuthors();
// 简单写法,通过map和reduce操作的显式组合,能更简单的表示
authors.stream()
.map(Author::getName)
//.reduce(String::concat) = .reduce((s, str) -> s.concat(str))字符串拼接
.reduce(String::concat)
.ifPresent(
System.out::println //蒙多亚拉索易易
);
// 当然如果只是简单的字符串拼接,完全可以直接使用Collectors.joining的连接函数来实现
String reduce2 = authors.stream()
.map(Author::getName)
.collect(Collectors.joining(","));
System.out.println(reduce2); //蒙多,亚拉索,易,易
reduce求sum
// 求年龄总和 (Integer::sum)方法引用
Integer sum = authors.stream().map(Author::getAge).reduce(Integer::sum).orElse(-1);
// 求年龄总和 (a, b) -> Integer.sum(a, b) lambda表达式
Integer sum = authors.stream().map(Author::getAge).reduce((a, b) -> Integer.sum(a, b)).orElse(-1);
sum()、average()
// 求年龄总和
Integer sum2 = authors.stream().mapToInt(Author::getAge).sum();
// 年龄的平均值
double average = authors.stream().mapToDouble(Author::getAge).average().orElse(0D);
注意事项
惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)
Optional
在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断
所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常
创建对象ofNullable()
Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。
我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题
ofNullable()方法底层就是Optional.of()+Optional.empty()
Author author = getAuthor();
Optional<Author> authorOptional = Optional.ofNullable(author);
如果确定一个对象不是空的则可以使用Optional的静态方法of来把数据封装成Optional对象
Author author = new Author();
Optional<Author> authorOptional = Optional.of(author);
如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional的静态方法empty来进行封装。
Optional.empty()
List<Author> authors = getAuthors();
Author author1 = authors.stream()
.filter(author -> author.getAge() > 33)
.min(Comparator.comparing(Author::getAge)).get();
Optional<Author> optionalAuthor = author1==null? Optional.empty() : Optional.of(author1);
//等同于上边的判断
Optional<Author> optionalAuthor2 = Optional.ofNullable(author1);
安全消费值ifPresent()
ifPresent()会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。就优雅的避免了空指针异常
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
//如果为空,不会消费
authorOptional.ifPresent(author -> System.out.println(author.getName()));
获取值get()
get()当Optional内部的数据为空的时候会出现异常
List<Author> authors = getAuthors();
Author author1 = authors.stream()
.distinct()
.filter(author -> author.getAge()>35)
.findFirst().get(); //java.util.NoSuchElementException: No value present
安全获取值orElseGet() orElseThrow()
orElseGet()获取数据,并且设置数据为空时的默认值
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
//当authorOptional中value为null时,将设置默认值new Author()
Author author1 = 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();
}
过滤filter()
filter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的Optional对象。
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
//过滤之后Optional是null,所以ifPresent后边的遍历不执行
authorOptional.filter(author -> author.getAge()>100).ifPresent(author -> System.out.println(author.getName()));
判断isPresent()
isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现Optional的好处,更推荐使用ifPresent方法。
Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
if (authorOptional.isPresent()) {
System.out.println(authorOptional.get().getName());
}
数据转换map()
map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。
Author author = getAuthor();
Optional<Author> authorOptional = Optional.ofNullable(author);
Optional<List<Book>> optionalBooks = authorOptional.map(author -> author.getBooks());
optionalBooks.ifPresent(books -> System.out.println(books));
函数式接口
只有一个抽象方法的接口我们称之为函数接口。
JDK的函数式接口都加上了**@FunctionalInterface** 注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。
Consumer 消费接口
Function 计算转换接口
Predicate 判断接口
Supplier 生产型接口
常用的默认方法,比如Predicate接口
and
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件
//打印作家中年龄大于17并且姓名的长度大于1的作家
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));
or
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。
//打印作家中年龄大于17或者姓名的长度小于2的作家。
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()<2;
}
})).forEach(author -> System.out.println(author.getName()));
negate
Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反
//打印作家中年龄不大于17的作家。
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时,如果方法体中只有一个方法的调用的话(包括构造方法),我们可以用方法引用进一步简化代码。
Alt+enter尝试是否可以转换成方法引用
类名或者对象名::方法名
如下代码就可以用方法引用进行简化
//优化前
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.map(author -> author.getAge())
.map(age->String.valueOf(age));
//优化后
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
authorStream.map(author -> author.getAge())
.map(String::valueOf);
//优化前
List<Author> authors = getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName())
.forEach(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);
//优化前
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.map(name->new StringBuilder(name))
.map(sb->sb.append("-三更").toString())
.forEach(str-> System.out.println(str));
//优化后
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.map(StringBuilder::new)
.map(sb->sb.append("-三更").toString())
.forEach(System.out::println);
Stream基本数据类型优化
Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。
即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候
Stream还提供了很多专门针对基本数据类型的方法
例如:mapToInt,mapToLong,mapToDouble,flatMapToInt,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);
authors.stream()
//mapToInt会直接使用int类型,无需一直自动装箱拆箱
.mapToInt(author -> author.getAge())
.map(age -> age + 10)
.filter(age->age>18)
.map(age->age+2)
.forEach(System.out::println);
并行流
当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完全。
parallel方法可以把串行流转换成并行流
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//parallel()使用并行流
Integer sum = stream.parallel()
//peek() stream提供的中间方法用于调试代码
.peek(num -> System.out.println(num+Thread.currentThread().getName()))
.filter(num -> num > 5)
.reduce((result, ele) -> result + ele)
.get();
System.out.println(sum);
parallelStream直接获取并行流对象
List<Author> authors = getAuthors();
authors.parallelStream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age->age>18)
.map(age->age+2)
.forEach(System.out::println);