- Lambda 表达式 - 就像快捷方式:
// 旧方式:冗长的匿名类
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击");
}
});
// Lambda方式:简洁明了
button.addActionListener(e -> System.out.println("按钮被点击"));
// 实际应用例子 - 排序
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// 旧方式
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
// Lambda方式
Collections.sort(names, (a, b) -> b.compareTo(a));
- Stream API - 就像流水线加工:
List<Employee> employees = Arrays.asList(
new Employee("张三", 5000),
new Employee("李四", 6000),
new Employee("王五", 7000)
);
// 旧方式:多步骤,代码冗长
List<String> highPaidNames = new ArrayList<>();
for (Employee e : employees) {
if (e.getSalary() > 5500) {
highPaidNames.add(e.getName().toUpperCase());
}
}
// Stream方式:流畅的链式操作
List<String> result = employees.stream()
.filter(e -> e.getSalary() > 5500) // 过滤高薪员工
.map(Employee::getName) // 提取名字
.map(String::toUpperCase) // 转换为大写
.collect(Collectors.toList()); // 收集结果
- 函数式接口 - 就像可重用的工具:
// Predicate - 判断条件
Predicate<Integer> isAdult = age -> age >= 18;
System.out.println(isAdult.test(20)); // true
// Consumer - 处理数据
Consumer<String> printer = message -> System.out.println("日志: " + message);
printer.accept("操作成功");
// Function - 数据转换
Function<String, Integer> stringToLength = String::length;
System.out.println(stringToLength.apply("Hello")); // 5
- 新的日期时间API - 更直观的时间处理:
// 旧方式:容易出错且不直观
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 1);
// 新方式:清晰直观
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
// 时区处理
ZonedDateTime tokyoTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println("东京时间:" + tokyoTime);
// 时间间隔计算
LocalDate birthDate = LocalDate.of(1990, 1, 1);
Period age = Period.between(birthDate, LocalDate.now());
System.out.println("年龄: " + age.getYears() + "年");
- 方法引用 - 更简洁的方法调用:
List<String> messages = Arrays.asList("hello", "world", "java");
// Lambda方式
messages.forEach(s -> System.out.println(s));
// 方法引用方式
messages.forEach(System.out::println);
// 实际应用例子
class PersonFactory {
public static Person createPerson(String name) {
return new Person(name);
}
}
// 使用方法引用创建对象
Function<String, Person> creator = PersonFactory::createPerson;
Person person = creator.apply("张三");
实际综合应用示例:
public class OrderProcessor {
public static void main(String[] args) {
List<Order> orders = Arrays.asList(
new Order("A001", 100.0, "PENDING"),
new Order("A002", 200.0, "COMPLETED"),
new Order("A003", 300.0, "PENDING")
);
// 使用Stream处理订单
double totalPending = orders.stream()
.filter(order -> "PENDING".equals(order.getStatus())) // Lambda过滤
.map(Order::getAmount) // 方法引用
.reduce(0.0, Double::sum); // 方法引用做归约
// 使用新的时间API记录处理时间
LocalDateTime processTime = LocalDateTime.now();
// 使用函数式接口处理结果
Consumer<String> logger = message ->
System.out.println(processTime + " - " + message);
logger.accept("待处理订单总金额: " + totalPending);
}
}
这些新特性的主要优势:
- 代码更简洁易读
- 更好的并行处理支持
- 更安全的日期时间处理
- 更灵活的函数式编程
- 更好的代码复用性
这些特性让Java编程变得更加现代化和高效。每个特性都像是一个新工具,帮助我们写出更好的代码。