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类型参数,返回booleanConsumer<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在冲突情况下的性能。