# LambdaAndStreamAndOptional **Repository Path**: su27sk/LambdaAndStreamAndOptional ## Basic Information - **Project Name**: LambdaAndStreamAndOptional - **Description**: 关于函数式编程的提升 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-02-14 - **Last Updated**: 2026-03-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: Java ## README # 函数式编程 ## lambda语法糖 - lamdba省略规则 ```angular2html 1.参数类型可以省略 2.方法体只有一句代码时大括号、return 和唯一一句代码的分号可以省略 3.方法只有一个参数时小括号可以省略 4.以上这些规则都记不住也可以省略不记 ``` ## 流操作 ### 中间操作 - filter ```angular2html private static void test04() { // 打印所有姓名长度大于1的作家姓名 List authors = getAuthors(); authors.stream() .filter(author -> author.getName().length() > 1) .forEach(author -> System.out.println(author)); } ``` - map ```angular2html private static void test05() { // 将作家转换为作家名字 List authors = getAuthors(); /* authors.stream(). map(new Function() { @Override public String apply(Author author) { return author.getName(); } }).forEach(System.out::println);*/ // 将每个作家年龄加十 authors.stream() .map(author -> author.getAge()) .map(age -> age + 10) .forEach(System.out::println); } ``` - distinct ```angular2html private static void test06() { // 去重操作 List authors = getAuthors(); authors.stream() .distinct() .forEach(author -> System.out.println(author.getName())); } ``` - sort ```angular2html private static void test07() { // 降序排序并去重 List authors = getAuthors(); /* authors.stream() .distinct() .sorted() .forEach(author -> System.out.println(author.getAge()));*/ authors.stream() .distinct() .sorted(new Comparator() { @Override public int compare(Author o1, Author o2) { return o2.getAge() - o1.getAge(); } }).forEach(author -> System.out.println(author.getAge())); } ``` - limit ```angular2html private static void test08() { // 降序后只取前个最大的 List authors = getAuthors(); authors.stream() .distinct() .sorted() .limit(2) .forEach(author -> System.out.println(author.getName())); } ``` - skip ```angular2html private static void test09() { // 跳过前一个元素,打印其他剩下的 List authors = getAuthors(); authors.stream() .distinct() .sorted() .skip(1) .forEach(author -> System.out.println(author.getName())); } ``` - flatMap ```angular2html private static void test11() { List authors = getAuthors(); authors.stream() .flatMap(author -> author.getBooks().stream()) .distinct() .flatMap(book -> Arrays.stream(book.getCategory().split(","))) .distinct() .forEach(category -> System.out.println(category)); } ``` ### 终结操作 - forEach ```azure private static void test12() { List authors = getAuthors(); authors.stream() .distinct() .map(author -> author.getName()) .forEach(name -> System.out.println(name)); } ``` - count ```azure private static void test13() { // 打印所有书籍的数量 List authors = getAuthors(); long count = authors.stream() .flatMap(author -> author.getBooks().stream()) .distinct() .count(); System.out.println(count); } ``` - max/min ```azure private static void test14() { // 获取所有书籍评分最高和最低的 List authors = getAuthors(); Optional max = authors.stream() .flatMap(author -> author.getBooks().stream()) .map(book -> book.getScore()) .max((score1, score2) -> score1 - score2); System.out.println(max); Optional min = authors.stream() .flatMap(author -> author.getBooks().stream()) .map(book -> book.getScore()) .min((score1, score2) -> score1 - score2); System.out.println(min); } ``` - collect ```azure private static void test17() { // 将作家名作为key,book作为value List authors = getAuthors(); Map> stringListMap = authors.stream() .distinct() .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks())); System.out.println(stringListMap); } private static void test16() { // 将所有书名转换为set集合 List authors = getAuthors(); Set NameSet = authors.stream() .flatMap(author -> author.getBooks().stream()) .map(book -> book.getName()) .distinct() .collect(Collectors.toSet()); System.out.println(NameSet); } private static void test15() { // 将所有作者名转换为list集合 List authors = getAuthors(); List nameList = authors.stream() .map(author -> author.getName()) .distinct() .collect(Collectors.toList()); System.out.println(nameList); } ``` - anyMatch ```azure private static void test18() { // 判断是否有年龄在29岁以上的作家 List authors = getAuthors(); boolean flag = authors.stream() .anyMatch(author -> author.getAge() > 29); System.out.println(flag); } ``` - allMatch ```azure private static void test19() { // 判断是否所有作家都是成年人 List authors = getAuthors(); boolean flag = authors.stream() .allMatch(author -> author.getAge() >= 18); System.out.println(flag); } ``` - noneMatch ```azure private static void test20() { // 判断是否所有作家都没有超过一百岁 List authors = getAuthors(); boolean flag = authors.stream() .noneMatch(author -> author.getAge() > 100); System.out.println(flag); } ``` - findAny ```azure private static void test21() { // 获取任意一个年龄>18的作家,如果存在就输出他的名字 List authors = getAuthors(); Optional optionalAuthor = authors.stream() .filter(author -> author.getAge() > 18) .findAny(); optionalAuthor.ifPresent(author -> System.out.println(author.getName())); } ``` - findFirst ```azure private static void test22() { // 获取一个年龄最小的作家,并输出他的姓名 List authors = getAuthors(); Optional optionalAuthor = authors.stream() .sorted((o1, o2) -> o1.getAge() - o2.getAge()) .findFirst(); optionalAuthor.ifPresent(author -> System.out.println(author.getName())); } ``` - reduce ```azure private static void test23() { // 使用reduce求所有作者年龄的和 List authors = getAuthors(); Integer reduce = authors.stream() .map(author -> author.getAge()) .distinct() .reduce(0, (result, element) -> result + element); System.out.println(reduce); } ``` ## Optional - ifPresent ```azure Optional authorOPtional = getAuthorOPtional(); /* ifPresent authorOPtional.ifPresent(author -> System.out.println(author));*/ ``` - orElseGet ```azure Optional authorOPtional = getAuthorOPtional(); /* orElseGet Author author = authorOPtional.orElseGet(() -> new Author(2L, "三大", 33, "裤衩子", null));*/ ``` - orElseThrow ```azure Optional authorOPtional = getAuthorOPtional(); /* orElseThrow try { Author author = authorOPtional.orElseThrow(()-> new RuntimeException("数据为null")); System.out.println(author); } catch (Throwable e) { throw new RuntimeException(e); }*/ ``` - isPresent ```azure private static void testIsPresent() { Optional authorOPtional = getAuthorOPtional(); if (authorOPtional.isPresent()) { System.out.println(authorOPtional.get().getName()); System.out.println(authorOPtional.get().getAge()); } } ``` - filter ```azure private static void testFilter() { Optional authorOPtional = getAuthorOPtional(); authorOPtional.filter(author -> author.getAge() > 18).ifPresent(author -> System.out.println(author.getName())); } ``` - map ```azure private static void testMap() { Optional authorOPtional = getAuthorOPtional(); authorOPtional.map(author -> author.getBooks()).ifPresent(books -> System.out.println(books)); } ``` ## 函数式接口 只有一个抽象方法的接口我们称之为函数接口。jdk的函数式接口都加上了@FunctionInterface注解进行标识。 ## 方法引用 方法引用是 Java 8 及以上版本中简化Lambda 表达式的语法糖 —— 简单说,当 Lambda 表达式里只是 “调用一个已存在的方法”,没有其他额外逻辑时,就可以用方法引用替代 Lambda,让代码更简洁、可读性更高。 ## Stream的一些高级操作 使用mapToInt避免频繁拆装箱影响性能 ```azure private static void test27() { List authors = getAuthors(); authors.stream() .mapToInt(author -> author.getAge()) .map(age -> age+10) .filter(age -> age > 18) .map(age -> age + 2) .forEach(System.out::println); } ``` 并行流 ```azure private static void test28() { Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 使用parallel改编为并行流,提高速度 Optional reduce = stream.parallel() .peek(num -> System.out.println(num + "---" + Thread.currentThread().getName())) .filter(num -> num > 5) .reduce((result, ele) -> result + ele); System.out.println(reduce.get()); // 使用parallelStream改编为并行流,提高速度 List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Optional reduce1 = list.parallelStream().peek(num -> System.out.println(num + "---" + Thread.currentThread().getName())) .filter(num -> num > 5) .reduce((result, ele) -> result + ele); System.out.println(reduce1.get()); } ```