al中包装的对象
@Test
public void test18() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
optionalAuthor
.filter(author -> author.getAge() > 14)
.ifPresent(author -> System.out.println(author));
}
// Optional的isPresent()方法,用来判断该Optional是否包装了对象
@Test
public void test19() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
boolean present = optionalAuthor.isPresent();
if (present) {
System.out.println(optionalAuthor.get().getName());
}
}
// Optional的map(),将一个 Optional 转换成另一个 Optional
@Test
public void test20() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
optionalAuthor.ifPresent(author -> System.out.println(author.getBooks()));
Optional<List<Book>> books = optionalAuthor.map(author -> author.getBooks());
books.ifPresent(books1 -> System.out.println(books.get()));
}
// 类的静态方法
@Test
public void test21() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(integer -> String.valueOf(integer));
// lambda方法体中只有一行代码
// .map(String::valueOf);
}
// 对象的实例方法
@Test
public void test22() {
List<Author> authors = S.getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName())
// lambda方法体中只有一行代码,且将参数全部按照顺序传入这个重写方法中
.forEach(str -> sb.append(str));
}
// 接口中只有一个抽象方法称为函数式接口
// 方法引用的条件是:lambda方法体中只有一行方法
// 构造器的方法引用
@Test
public void test23() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(Author::getName)
.map(StringBuilder::new)
.map(stringBuilder -> stringBuilder.append("abc"))
.forEach(System.out::println);
}
// steam提供的处理基本数据类型,避免频繁的自动拆/装箱,从而达到省时,提高性能
@Test
public void test24() {
List<Author> authors = S.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(author -> author.getAge())
.map(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age + 2)
.forEach(System.out::println);
}
@Test
public void test25() {
List<Author> authors = S.getAuthors();
authors.stream()
.parallel()
.map(author -> author.getAge())
.peek(integer -> System.out.println(integer+" "+Thread.currentThread().getName()))
.reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer ele) {
return result + ele;
}
}).ifPresent(sum -> System.out.println(sum));
}
}
lambda表达式
lambda表达式只关心 形参列表 和 方法体
用在重写抽象方法的时候,一般都是采用lambda表达式的方式来重写
函数式接口
函数式接口:接口中只有一个抽象方法,就称之为函数式接口。在Java中Consumer,Funciton,Supplier
方法引用
方法引用:当lambda表达式的方法体中只有一行代码,并且符合一些规则,就可以将该行代码转换成方法引用的形式
可以直接使用idea的提示自动转换
这只是一个语法糖,能看懂代码就行,不要过于纠结