-> score1 - score2);
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.min((score1, score2) -> score1 - score2);
System.out.println(max.get());
System.out.println(min.get());
}
// stream 的 collect()
@Test
public void test9() {
// 获取所有作者名字
List<Author> authors = S.getAuthors();
Set<String> collect = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toSet());
System.out.println(collect);
//获取一个所有书名的Set集合。
Set<String> collect1 = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.collect(Collectors.toSet());
System.out.println(collect1);
// 获取一个Map集合,map的key为作者名,value为List<Book>
Map<String, List<Book>> collect2 = authors.stream()
.distinct()
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(collect2);
}
// anyMatch
@Test
public void test10() {
List<Author> authors = S.getAuthors();
boolean b = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(b);
}
// allMatch
@Test
public void test11() {
List<Author> authors = S.getAuthors();
boolean b = authors.stream()
.allMatch(author -> author.getAge() > 18);
System.out.println(b);
}
// findFirst
@Test
public void test12() {
List<Author> authors = S.getAuthors();
Optional<Author> first = authors.stream()
.sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
.findFirst();
first.ifPresent(author -> System.out.println(author));
}
// reduce() 的使用
@Test
public void test13() {
// 使用reduce求所有作者年龄的和
List<Author> authors = S.getAuthors();
Integer sum = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(0, (result, element) -> result + element);
// .reduce(0, (result, element) -> result + element);
System.out.println(sum);
}
@Test
public void test14() {
// 使用reduce求所有作者中年龄的最小值
List<Author> authors = S.getAuthors();
Integer minAge = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (res, ele) -> res > ele ? ele : res);
System.out.println(minAge);
}
// 没有初始值的reduce()使用
@Test
public void test15() {
List<Author> authors = S.getAuthors();
Optional<Integer> age = authors.stream()
.map(author -> author.getAge())
.reduce((res, ele) -> res > ele ? ele : res);
System.out.println(age.get());
}
// Optional对象的封装,orElseGet的使用
@Test
public void test16() {
Optional<Author> authorOptional = Optional.ofNullable(null);
Author author1 = authorOptional.orElseGet(() -> new Author(1l, "1", 1, "1", null));
System.out.println(author1);
// authorOptional.ifPresent(author -> System.out.println(author.getName()));
}
@Test
public void test17() {
Optional<Author> authorOptional = Optional.ofNullable(null);
try {
Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("exception"));
System.out.println(author.getName());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
// Optional的filter()方法
// ifPresent()可以安全消费Option |