Java 8作为Java语言的一个重要版本,引入了诸多新特性和改进,使得编程更加高效、简洁。以下是Java 8的核心特性,结合实战案例,帮助你轻松上手这些新功能。
1. Lambda表达式
Lambda表达式是Java 8引入的最具革命性的特性之一,它允许开发者以更简洁的方式编写函数式接口。
实战案例:使用Lambda表达式处理集合
假设我们有一个学生类Student,包含姓名和成绩,我们想要打印出所有成绩超过90分的学生姓名。
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 92),
new Student("Bob", 85),
new Student("Charlie", 95),
new Student("David", 78)
);
List<String> highScores = students.stream()
.filter(s -> s.getScore() > 90)
.map(Student::getName)
.collect(Collectors.toList());
highScores.forEach(System.out::println);
}
}
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
2. Stream API
Stream API是Java 8提供的用于处理集合数据的新工具,它基于Lambda表达式,使得集合操作更加简洁。
实战案例:使用Stream API计算平均值
我们想要计算一个整数列表的平均值。
import java.util.Arrays;
import java.util.OptionalDouble;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
OptionalDouble average = numbers.stream()
.mapToInt(Integer::intValue)
.average();
if (average.isPresent()) {
System.out.println("Average: " + average.getAsDouble());
} else {
System.out.println("No elements to calculate average.");
}
}
}
3. Date-Time API
Java 8对日期和时间处理进行了重大改进,引入了新的java.time包。
实战案例:使用Date-Time API获取当前时间
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date and time: " + now);
}
}
4. Optional类
Optional类是Java 8为避免空指针异常而引入的,它提供了一种更加优雅的方式来处理可能为null的对象。
实战案例:使用Optional处理可能为null的值
import java.util.Optional;
public class Main {
public static void main(String[] args) {
String name = Optional.ofNullable(getName()).orElse("Unknown");
System.out.println("Name: " + name);
}
private static String getName() {
// 模拟可能返回null的方法
return null;
}
}
5. 新的并发API
Java 8提供了新的并发API,如CompletableFuture,使得并发编程更加容易。
实战案例:使用CompletableFuture实现异步编程
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Background task started.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Background task completed.");
});
future.thenRun(() -> System.out.println("Main thread continues."));
}
}
通过以上实战案例,你可以看到Java 8的新特性如何简化编程任务。掌握这些特性将使你的Java编程更加高效和强大。
