// Java 8 新特性示例代码
// 1. Lambda 表达式
// 传统方式
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(new Consumer<String>() {
@Override
public void accept(String name) {
System.out.println(name);
}
});
// 使用 Lambda 表达式
names.forEach(name -> System.out.println(name));
// 或者更简洁的方式
names.forEach(System.out::println);
// 2. Stream API
// 传统方式
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = new ArrayList<>();
for (Integer number : numbers) {
if (number % 2 == 0) {
evenNumbers.add(number);
}
}
// 使用 Stream API
List<Integer> evenNumbersStream = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// 3. 默认方法和静态方法接口
interface MyInterface {
// 默认方法
default void myDefaultMethod() {
System.out.println("This is a default method.");
}
// 静态方法
static void myStaticMethod() {
System.out.println("This is a static method.");
}
}
class MyClass implements MyInterface {
// 不需要实现默认方法,但可以选择重写
}
// 4. Optional 类
Optional<String> optionalName = Optional.ofNullable("John");
optionalName.ifPresent(name -> System.out.println("Hello, " + name));
// 5. 日期时间 API (java.time 包)
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date and time: " + now);
LocalDate date = LocalDate.of(2023, 10, 1);
System.out.println("Specific date: " + date);
Duration duration = Duration.between(LocalTime.of(10, 30), LocalTime.of(11, 15));
System.out.println("Duration between times: " + duration.toMinutes() + " minutes");
Period period = Period.between(LocalDate.of(2023, 1, 1), LocalDate.of(2023, 10, 1));
System.out.println("Period between dates: " + period.getMonths() + " months");
// 6. 方法引用
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("Hello, " + name);
}
}
List<Person> people = Arrays.asList(new Person("Alice"), new Person("Bob"));
people.forEach(Person::sayHello);
null 值引发的 NullPointerException,提供了一种更优雅的处理方式。LocalDateTime、LocalDate、Duration 和 Period,提供了更强大的日期和时间处理功能。上一篇:水仙花数java方法怎么写
下一篇:java repository
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站