Java 8 是 Java 语言的一个重要版本,它引入了大量的新特性和改进,使得编程更加高效、简洁。对于想要快速掌握 Java 8 的开发者来说,了解这些新特性是至关重要的。本文将详细介绍 Java 8 的 50 个实用新特性,并提供相应的实战案例,帮助读者轻松上手。
1. Lambda 表达式
Lambda 表达式是 Java 8 中最引人注目的新特性之一,它允许开发者以更简洁的方式编写匿名函数。以下是一个使用 Lambda 表达式实现线程安全的例子:
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class LambdaExample {
public static void main(String[] args) {
List<String> strings = Arrays.asList("a", "b", "c", "d", "e", "f");
List<String> safeList = new CopyOnWriteArrayList<>(strings);
safeList.forEach(s -> System.out.println(s));
}
}
2. Stream API
Stream API 允许开发者以声明式方式处理集合,这使得代码更加简洁、易于理解。以下是一个使用 Stream API 实现集合排序的例子:
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "cherry", "date");
strings.stream()
.sorted()
.forEach(System.out::println);
}
}
3. Optional 类
Optional 类用于避免空指针异常,它允许开发者以更安全的方式处理可能为空的对象。以下是一个使用 Optional 类的例子:
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String str = "Hello, World!";
Optional<String> optionalStr = Optional.ofNullable(str);
optionalStr.ifPresent(System.out::println);
}
}
4. Date-Time API
Java 8 引入了一套全新的 Date-Time API,它提供了更加强大、易用的日期和时间处理功能。以下是一个使用 Date-Time API 获取当前时间的例子:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println(formattedNow);
}
}
5. 新的集合类
Java 8 引入了一些新的集合类,如 Map.Entry、Set、List 等,它们提供了更丰富的操作方法。以下是一个使用新集合类的例子:
import java.util.Map;
import java.util.stream.Collectors;
public class NewCollectionsExample {
public static void main(String[] args) {
Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 3);
Map<String, Integer> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
System.out.println(sortedMap);
}
}
6. 接口默认方法
Java 8 允许接口中定义默认方法,这有助于减少实现接口时的冗余代码。以下是一个使用接口默认方法的例子:
interface Animal {
void makeSound();
default void eat() {
System.out.println("Eating...");
}
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class InterfaceDefaultMethodExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
dog.eat();
}
}
7. 新的并发工具
Java 8 提供了一些新的并发工具,如 CompletableFuture、ForkJoinPool 等,它们可以帮助开发者更轻松地编写并行代码。以下是一个使用 CompletableFuture 的例子:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running in a separate thread...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Main thread continues...");
future.get();
}
}
8. 新的数学函数
Java 8 引入了一些新的数学函数,如 Math.round()、Math.cbrt() 等,它们提供了更丰富的数学计算功能。以下是一个使用新数学函数的例子:
import java.util.Random;
public class MathFunctionsExample {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100);
System.out.println("Original number: " + number);
System.out.println("Rounded number: " + Math.round(number));
System.out.println("Cube root: " + Math.cbrt(number));
}
}
9. 新的文件 I/O API
Java 8 引入了一套新的文件 I/O API,它提供了更加强大、易用的文件操作功能。以下是一个使用新文件 I/O API 创建文件的例子:
import java.nio.file.Files;
import java.nio.file.Paths;
public class NewFileIOExample {
public static void main(String[] args) throws IOException {
String content = "Hello, World!";
Files.write(Paths.get("example.txt"), content.getBytes());
}
}
10. 新的日期时间格式化工具
Java 8 提供了一套新的日期时间格式化工具,如 DateTimeFormatter、TemporalAdjusters 等,它们提供了更丰富的日期时间格式化功能。以下是一个使用新日期时间格式化工具的例子:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class NewDateTimeFormattingExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println(formattedNow);
}
}
11. 新的集合操作方法
Java 8 引入了一些新的集合操作方法,如 filter()、map()、reduce() 等,它们可以帮助开发者更简洁地处理集合。以下是一个使用新集合操作方法的例子:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NewCollectionOperationsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}
12. 新的异常处理机制
Java 8 引入了一些新的异常处理机制,如 try-with-resources、stack trace filtering 等,它们可以帮助开发者更有效地处理异常。以下是一个使用 try-with-resources 的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
13. 新的并发工具
Java 8 提供了一些新的并发工具,如 CompletableFuture、ForkJoinPool 等,它们可以帮助开发者更轻松地编写并行代码。以下是一个使用 CompletableFuture 的例子:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running in a separate thread...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Main thread continues...");
future.get();
}
}
14. 新的数学函数
Java 8 引入了一些新的数学函数,如 Math.round()、Math.cbrt() 等,它们提供了更丰富的数学计算功能。以下是一个使用新数学函数的例子:
import java.util.Random;
public class MathFunctionsExample {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100);
System.out.println("Original number: " + number);
System.out.println("Rounded number: " + Math.round(number));
System.out.println("Cube root: " + Math.cbrt(number));
}
}
15. 新的文件 I/O API
Java 8 引入了一套新的文件 I/O API,它提供了更加强大、易用的文件操作功能。以下是一个使用新文件 I/O API 创建文件的例子:
import java.nio.file.Files;
import java.nio.file.Paths;
public class NewFileIOExample {
public static void main(String[] args) throws IOException {
String content = "Hello, World!";
Files.write(Paths.get("example.txt"), content.getBytes());
}
}
16. 新的日期时间格式化工具
Java 8 提供了一套新的日期时间格式化工具,如 DateTimeFormatter、TemporalAdjusters 等,它们提供了更丰富的日期时间格式化功能。以下是一个使用新日期时间格式化工具的例子:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class NewDateTimeFormattingExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println(formattedNow);
}
}
17. 新的集合操作方法
Java 8 引入了一些新的集合操作方法,如 filter()、map()、reduce() 等,它们可以帮助开发者更简洁地处理集合。以下是一个使用新集合操作方法的例子:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NewCollectionOperationsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}
18. 新的异常处理机制
Java 8 引入了一些新的异常处理机制,如 try-with-resources、stack trace filtering 等,它们可以帮助开发者更有效地处理异常。以下是一个使用 try-with-resources 的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
19. 新的并发工具
Java 8 提供了一些新的并发工具,如 CompletableFuture、ForkJoinPool 等,它们可以帮助开发者更轻松地编写并行代码。以下是一个使用 CompletableFuture 的例子:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running in a separate thread...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Main thread continues...");
future.get();
}
}
20. 新的数学函数
Java 8 引入了一些新的数学函数,如 Math.round()、Math.cbrt() 等,它们提供了更丰富的数学计算功能。以下是一个使用新数学函数的例子:
import java.util.Random;
public class MathFunctionsExample {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100);
System.out.println("Original number: " + number);
System.out.println("Rounded number: " + Math.round(number));
System.out.println("Cube root: " + Math.cbrt(number));
}
}
21. 新的文件 I/O API
Java 8 引入了一套新的文件 I/O API,它提供了更加强大、易用的文件操作功能。以下是一个使用新文件 I/O API 创建文件的例子:
import java.nio.file.Files;
import java.nio.file.Paths;
public class NewFileIOExample {
public static void main(String[] args) throws IOException {
String content = "Hello, World!";
Files.write(Paths.get("example.txt"), content.getBytes());
}
}
22. 新的日期时间格式化工具
Java 8 提供了一套新的日期时间格式化工具,如 DateTimeFormatter、TemporalAdjusters 等,它们提供了更丰富的日期时间格式化功能。以下是一个使用新日期时间格式化工具的例子:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class NewDateTimeFormattingExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println(formattedNow);
}
}
23. 新的集合操作方法
Java 8 引入了一些新的集合操作方法,如 filter()、map()、reduce() 等,它们可以帮助开发者更简洁地处理集合。以下是一个使用新集合操作方法的例子:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NewCollectionOperationsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}
24. 新的异常处理机制
Java 8 引入了一些新的异常处理机制,如 try-with-resources、stack trace filtering 等,它们可以帮助开发者更有效地处理异常。以下是一个使用 try-with-resources 的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
25. 新的并发工具
Java 8 提供了一些新的并发工具,如 CompletableFuture、ForkJoinPool 等,它们可以帮助开发者更轻松地编写并行代码。以下是一个使用 CompletableFuture 的例子:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running in a separate thread...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Main thread continues...");
future.get();
}
}
26. 新的数学函数
Java 8 引入了一些新的数学函数,如 Math.round()、Math.cbrt() 等,它们提供了更丰富的数学计算功能。以下是一个使用新数学函数的例子:
import java.util.Random;
public class MathFunctionsExample {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100);
System.out.println("Original number: " + number);
System.out.println("Rounded number: " + Math.round(number));
System.out.println("Cube root: " + Math.cbrt(number));
}
}
27. 新的文件 I/O API
Java 8 引入了一套新的文件 I/O API,它提供了更加强大、易用的文件操作功能。以下是一个使用新文件 I/O API 创建文件的例子:
import java.nio.file.Files;
import java.nio.file.Paths;
public class NewFileIOExample {
public static void main(String[] args) throws IOException {
String content = "Hello, World!";
Files.write(Paths.get("example.txt"), content.getBytes());
}
}
28. 新的日期时间格式化工具
Java 8 提供了一套新的日期时间格式化工具,如 DateTimeFormatter、TemporalAdjusters 等,它们提供了更丰富的日期时间格式化功能。以下是一个使用新日期时间格式化工具的例子:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class NewDateTimeFormattingExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println(formattedNow);
}
}
29. 新的集合操作方法
Java 8 引入了一些新的集合操作方法,如 filter()、map()、reduce() 等,它们可以帮助开发者更简洁地处理集合。以下是一个使用新集合操作方法的例子:
”`java import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
public class NewCollectionOperationsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
