当前位置: 首页 > java >正文

Java8特性

一、Lambda表达式

Lambda表达式是Java 8引入的重要特性,允许将函数作为参数传递,实现函数式编程。

1.1 语法结构

(parameters) -> expression
或
(parameters) -> { statements; }

1.2 示例

// 无参数
() -> System.out.println("Hello Lambda");// 单参数
(x) -> x * x// 多参数
(x, y) -> x + y// 代码块
(x, y) -> {int sum = x + y;return sum;
}

1.3 使用场景

  • 简化匿名内部类代码
  • 作为函数式接口的实例
  • 与Stream API结合使用

二、函数式接口

函数式接口是只包含一个抽象方法的接口,使用@FunctionalInterface注解标识。

2.1 常见函数式接口

  • Predicate<T>: 接收T类型参数,返回boolean
  • Consumer<T>: 接收T类型参数,无返回值
  • Function<T, R>: 接收T类型参数,返回R类型结果
  • Supplier<T>: 无参数,返回T类型结果

2.2 示例

@FunctionalInterface
interface MyFunction {int apply(int a, int b);
}MyFunction add = (a, b) -> a + b;
System.out.println(add.apply(3, 5)); // 输出: 8

三、Stream API

Stream API提供了对集合数据的函数式操作,支持过滤、映射、聚合等操作。

3.1 主要操作

  • 中间操作: filter、map、sorted、distinct、limit等
  • 终端操作: collect、forEach、reduce、count、anyMatch等

3.2 示例

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");// 过滤以"A"开头的名字并转换为大写
List<String> result = names.stream().filter(name -> name.startsWith("A")).map(String::toUpperCase).collect(Collectors.toList());System.out.println(result); // 输出: [ALICE]

3.3 并行流

通过parallelStream()创建并行流,利用多核处理器提高性能:

int sum = numbers.parallelStream().filter(n -> n % 2 == 1).mapToInt(Integer::intValue).sum();

四、Optional类

Optional类用于处理可能为null的值,避免空指针异常。

4.1 主要方法

  • of(T value): 创建非空Optional对象
  • ofNullable(T value): 创建可能为空的Optional对象
  • empty(): 创建空Optional对象
  • isPresent(): 判断值是否存在
  • ifPresent(Consumer<? super T> consumer): 值存在时执行操作
  • orElse(T other): 值不存在时返回默认值
  • map(Function<? super T, ? extends U> mapper): 映射值

4.2 示例

Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(n -> System.out.println("Hello, " + n));String defaultName = name.orElse("Unknown");

五、接口的默认方法和静态方法

Java 8允许接口中定义默认方法和静态方法。

5.1 默认方法

使用default关键字定义,实现类可以继承或重写:

public interface MyInterface {default void defaultMethod() {System.out.println("Default method");}
}

5.2 静态方法

接口中可以定义静态方法,提供工具功能:

public interface MyInterface {static void staticMethod() {System.out.println("Static method");}
}

六、方法引用

方法引用提供了一种引用已有方法的简洁方式。

6.1 类型

  • 静态方法引用: ClassName::staticMethod
  • 实例方法引用: instance::instanceMethod
  • 对象方法引用: ClassName::instanceMethod
  • 构造方法引用: ClassName::new

6.2 示例

// 静态方法引用
List<Integer> numbers = Arrays.asList(3, 1, 2);
numbers.sort(Integer::compare);// 对象方法引用
String str = "Hello";
Supplier<Integer> lengthSupplier = str::length;

七、新日期时间API

Java 8引入了java.time包,提供了全新的日期时间处理API。

7.1 主要类

  • LocalDate: 日期(年、月、日)
  • LocalTime: 时间(时、分、秒)
  • LocalDateTime: 日期和时间
  • ZonedDateTime: 带时区的日期时间
  • Instant: 时间戳
  • Period: 日期间隔
  • Duration: 时间间隔

7.2 示例

// 获取当前日期
LocalDate today = LocalDate.now();// 创建指定日期
LocalDate specificDate = LocalDate.of(2024, 9, 2);// 日期计算
LocalDate tomorrow = today.plusDays(1);// 格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = today.format(formatter);

八、其他特性

8.1 Nashorn JavaScript引擎

替代Rhino引擎,支持在JVM中执行JavaScript代码:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello Nashorn');");

8.2 重复注解

使用@Repeatable注解实现重复注解:

@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {String value();
}@MyAnnotation("value1")
@MyAnnotation("value2")
public class MyClass {}

8.3 类型注解

允许在任何使用类型的地方添加注解,增强类型检查:

List<@NonNull String> list;

8.4 HashMap性能优化

针对哈希冲突,Java 8引入红黑树结构,提高HashMap在冲突情况下的性能。

http://www.xdnf.cn/news/19834.html

相关文章:

  • 【HarmonyOS 6】仿AI唤起屏幕边缘流光特效
  • leetcode-每日一题-人员站位的方案数-C语言
  • Spring 循环依赖问题
  • 《LINUX系统编程》笔记p8
  • 大模型RAG项目实战:RAG技术原理及核心架构
  • SpringBoot 事务管理避坑指南
  • 机器学习:从技术原理到实践应用的深度解析
  • 机器人抓取中的力学相关概念解释
  • JVM中产生OOM(内存溢出)的8种典型情况及解决方案
  • 初识NOSQL
  • 方法决定效率
  • git: 取消文件跟踪
  • SRE团队是干嘛的
  • 关于IDE的相关知识之一【使用技巧】
  • Spring Security 如何使用@PreAuthorize注解
  • Nano Banana 新玩法超惊艳!附教程案例提示词!
  • AI 设计工具天花板
  • 【android bluetooth 协议分析 21】【ble 介绍 3】【ble acl Supervision Timeout 介绍】
  • 黑马头条面试重点业务
  • 构建下一代智能金融基础设施
  • SpringBoot--手写日期格式转换工具类
  • TiDB v8.5.3 单机集群部署指南
  • ASP.NET Core上传文件到minio
  • 【leetcode】236. 二叉树的最近公共祖先
  • 利用Base64传输二进制文件并执行的方法(适合没有ssh ftp等传输工具的嵌入式离线场景)
  • 研发文档版本混乱的根本原因是什么,怎么办
  • ELK 统一日志分析系统部署与实践指南(上)
  • 撤销修改 情况⼀:对于⼯作区的代码,还没有 add
  • 餐饮、跑腿、零售多场景下的同城外卖系统源码扩展方案
  • 图片移到根目录