欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 小白借助ai对全栈进行浅浅理解(学习笔记)-Lambda、Optional 避免空指针与新的日期时间 API

小白借助ai对全栈进行浅浅理解(学习笔记)-Lambda、Optional 避免空指针与新的日期时间 API

2025/5/9 8:44:03 来源:https://blog.csdn.net/2301_78571744/article/details/147804400  浏览:    关键词:小白借助ai对全栈进行浅浅理解(学习笔记)-Lambda、Optional 避免空指针与新的日期时间 API

学习顺序:Java 基础 → Spring Boot → Vue → 前后端整合 → 数据库 → 部署 → 进阶实战。

 Lambda 表达式(Lambda 表达式是 Java 8 引入的核心特性,旨在简化函数式编程,替代冗长的匿名内部类,使代码更简洁、灵活 

Lambda 必须与函数式接口(Functional Interface) 配合使用,即接口中仅有一个抽象方法。

@FunctionalInterface//自定义函数接口interface Calculator {int operate(int a, int b);}// 使用 Lambda 实现加法Calculator add = (a, b) -> a + b;System.out.println(add.operate(3, 5)); // 输出 8

// 静态方法引用
Function<Double, Double> sqrt = Math::sqrt;
// 实例方法引用
List<String> names = Arrays.asList("Alice", "Bob");
names.forEach(System.out::println); // 等效于 s -> System.out.println(s)
// 构造器引用
Supplier<List<String>> listSupplier = ArrayList::new;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 过滤偶数,平方后求和
int sum = numbers.stream().filter(n -> n % 2 == 0)    // Predicate.map(n -> n * n)            // Function.reduce(0, Integer::sum);   // BinaryOperator
System.out.println(sum); // 输出 20 (2² + 4² = 4 + 16)

// 显式类型
Comparator<Integer> cmp = (Integer a, Integer b) -> a.compareTo(b);
// 隐式类型(推荐)
Comparator<Integer> cmp = (a, b) -> a.compareTo(b);

@FunctionalInterface
interface FileProcessor {void process() throws IOException; // 声明异常
}
FileProcessor processor = () -> Files.readAllBytes(Paths.get("file.txt"));

错误堆栈中直接显示processString,明确指出问题发生在processString方法中,方便快速定位

集合排序中,a.length()-b.length()[从小到大]    b.length()-a.length()[从大到小]

Optional 避免空指针、新的日期时间 API

链式处理就是.map().filter();

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词