java不同版本特性示例
This commit is contained in:
141
demo2/java8-example/README.md
Normal file
141
demo2/java8-example/README.md
Normal file
@@ -0,0 +1,141 @@
|
||||
Java 8 特性示例项目
|
||||
---
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
|
||||
src/main/java/
|
||||
├── Main.java // 主程序入口
|
||||
├── LambdaExample.java // Lambda表达式示例
|
||||
├── StreamExample.java // Stream API示例
|
||||
├── OptionalExample.java // Optional类示例
|
||||
├── DateTimeExample.java // 新日期时间API示例
|
||||
└── FunctionExample.java // 函数式接口示例
|
||||
```
|
||||
## Java 8 特性详解
|
||||
|
||||
### 1. Lambda 表达式 (LambdaExample.java)
|
||||
|
||||
Lambda表达式是Java 8最重要的新特性之一,它允许把函数作为一个方法的参数(函数作为参数传递)。
|
||||
|
||||
主要示例:
|
||||
- Runnable接口的Lambda简化写法
|
||||
- 集合排序的Lambda表达式用法
|
||||
- 不同形式的Lambda表达式语法
|
||||
|
||||
```
|
||||
java
|
||||
// 传统匿名内部类
|
||||
Runnable oldRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("传统方式执行Runnable");
|
||||
}
|
||||
};
|
||||
|
||||
// Lambda表达式
|
||||
Runnable newRunnable = () -> System.out.println("Lambda方式执行Runnable");
|
||||
```
|
||||
### 2. Stream API (StreamExample.java)
|
||||
|
||||
Stream API是Java 8中处理集合的关键抽象概念,它可以对集合进行各种操作,如过滤、映射、排序等。
|
||||
|
||||
主要示例:
|
||||
- filter() 过滤操作
|
||||
- map() 映射操作
|
||||
- collect() 收集操作
|
||||
- findFirst() 查找操作
|
||||
- parallelStream() 并行流处理
|
||||
|
||||
```
|
||||
java
|
||||
// 过滤年龄大于25的人
|
||||
List<Person> filtered = people.stream()
|
||||
.filter(person -> person.getAge() > 25)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 提取所有人的姓名
|
||||
List<String> names = people.stream()
|
||||
.map(Person::getName)
|
||||
.collect(Collectors.toList());
|
||||
```
|
||||
### 3. Optional 类 (OptionalExample.java)
|
||||
|
||||
Optional类是一个可以为null的容器对象,用来避免空指针异常,更好地处理可能为null的值。
|
||||
|
||||
主要示例:
|
||||
- of() 和 empty() 创建Optional对象
|
||||
- isPresent() 判断是否有值
|
||||
- orElse() 提供默认值
|
||||
- ifPresent() 存在时执行操作
|
||||
- map() 转换值
|
||||
|
||||
```
|
||||
java
|
||||
Optional<String> optional = Optional.of("Hello Java 8");
|
||||
Optional<String> emptyOptional = Optional.empty();
|
||||
|
||||
// 使用orElse提供默认值
|
||||
String value = emptyOptional.orElse("默认值");
|
||||
|
||||
// 使用ifPresent执行操作
|
||||
optional.ifPresent(s -> System.out.println("处理值: " + s.toUpperCase()));
|
||||
```
|
||||
### 4. 新的日期时间API (DateTimeExample.java)
|
||||
|
||||
Java 8引入了新的日期时间API(java.time包),解决了之前Date和Calendar类的缺陷。
|
||||
|
||||
主要示例:
|
||||
- LocalDate 只包含日期
|
||||
- LocalDateTime 包含日期和时间
|
||||
- DateTimeFormatter 日期格式化
|
||||
- plusWeeks(), minusMonths() 日期计算
|
||||
|
||||
```
|
||||
java
|
||||
// LocalDate示例
|
||||
LocalDate today = LocalDate.now();
|
||||
LocalDate specificDate = LocalDate.of(2025, 7, 18);
|
||||
|
||||
// LocalDateTime示例
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// 日期格式化
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
String formattedDate = now.format(formatter);
|
||||
```
|
||||
### 5. 函数式接口 (FunctionExample.java)
|
||||
|
||||
Java 8提供了许多内置的函数式接口,如Predicate、Consumer、Function、Supplier等。
|
||||
|
||||
主要示例:
|
||||
- Predicate 用于判断操作
|
||||
- Consumer 用于消费数据
|
||||
- Function 用于数据转换
|
||||
- Supplier 用于生成数据
|
||||
|
||||
```
|
||||
java
|
||||
// Predicate示例
|
||||
Predicate<Integer> isEven = n -> n % 2 == 0;
|
||||
|
||||
// Consumer示例
|
||||
Consumer<String> printer = System.out::println;
|
||||
|
||||
// Function示例
|
||||
java.util.function.Function<String, Integer> stringToLength = String::length;
|
||||
|
||||
// Supplier示例
|
||||
java.util.function.Supplier<Double> randomSupplier = Math::random;
|
||||
```
|
||||
|
||||
## 学习建议
|
||||
|
||||
建议按以下顺序学习Java 8特性:
|
||||
1. 先理解Lambda表达式的基本语法
|
||||
2. 学习函数式接口的概念
|
||||
3. 掌握Stream API的常用操作
|
||||
4. 熟悉Optional类的使用场景
|
||||
5. 了解新的日期时间API的优势
|
||||
|
||||
31
demo2/java8-example/pom.xml
Normal file
31
demo2/java8-example/pom.xml
Normal file
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>top.yexuejc</groupId>
|
||||
<artifactId>java8-example</artifactId>
|
||||
<version>1.0.0</version>
|
||||
|
||||
<properties>
|
||||
<java.version>8</java.version>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
40
demo2/java8-example/src/main/java/DateTimeExample.java
Normal file
40
demo2/java8-example/src/main/java/DateTimeExample.java
Normal file
@@ -0,0 +1,40 @@
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* @author maxiaofeng
|
||||
* @date 2025/8/5 13:53
|
||||
*/
|
||||
public class DateTimeExample {
|
||||
/**
|
||||
* 新的日期时间API示例
|
||||
* Java 8引入了新的日期时间API,解决了之前Date和Calendar类的缺陷
|
||||
*/
|
||||
static void dateTimeExample() {
|
||||
System.out.println("\n=== 新日期时间API示例 ===");
|
||||
|
||||
// LocalDate示例 - 只包含日期
|
||||
LocalDate today = LocalDate.now();
|
||||
System.out.println("今天的日期: " + today);
|
||||
|
||||
LocalDate specificDate = LocalDate.of(2025, 7, 18);
|
||||
System.out.println("指定日期: " + specificDate);
|
||||
|
||||
// LocalDateTime示例 - 包含日期和时间
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
System.out.println("当前日期时间: " + now);
|
||||
|
||||
// 日期格式化
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
String formattedDate = now.format(formatter);
|
||||
System.out.println("格式化后的日期时间: " + formattedDate);
|
||||
|
||||
// 日期计算
|
||||
LocalDate nextWeek = today.plusWeeks(1);
|
||||
System.out.println("下周的日期: " + nextWeek);
|
||||
|
||||
LocalDate lastMonth = today.minusMonths(1);
|
||||
System.out.println("上个月的日期: " + lastMonth);
|
||||
}
|
||||
}
|
||||
36
demo2/java8-example/src/main/java/FunctionExample.java
Normal file
36
demo2/java8-example/src/main/java/FunctionExample.java
Normal file
@@ -0,0 +1,36 @@
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* @author maxiaofeng
|
||||
* @date 2025/8/5 13:53
|
||||
*/
|
||||
public class FunctionExample {
|
||||
/**
|
||||
* 函数式接口示例
|
||||
* Java 8提供了许多内置的函数式接口
|
||||
*/
|
||||
static void functionalInterfaceExample() {
|
||||
System.out.println("\n=== 函数式接口示例 ===");
|
||||
|
||||
// Predicate示例 - 用于判断
|
||||
Predicate<Integer> isEven = n -> n % 2 == 0;
|
||||
System.out.println("10是偶数吗? " + isEven.test(10));
|
||||
System.out.println("11是偶数吗? " + isEven.test(11));
|
||||
|
||||
// Consumer示例 - 用于消费数据
|
||||
Consumer<String> printer = System.out::println;
|
||||
printer.accept("使用Consumer打印信息");
|
||||
|
||||
// Function示例 - 用于转换
|
||||
java.util.function.Function<String, Integer> stringToLength = String::length;
|
||||
int length = stringToLength.apply("Java 8");
|
||||
System.out.println("字符串'Java 8'的长度: " + length);
|
||||
|
||||
// Supplier示例 - 用于生成数据
|
||||
java.util.function.Supplier<Double> randomSupplier = Math::random;
|
||||
System.out.println("随机数: " + randomSupplier.get());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
51
demo2/java8-example/src/main/java/LambdaExample.java
Normal file
51
demo2/java8-example/src/main/java/LambdaExample.java
Normal file
@@ -0,0 +1,51 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author maxiaofeng
|
||||
* @date 2025/8/5 13:51
|
||||
*/
|
||||
public class LambdaExample {
|
||||
|
||||
/**
|
||||
* Lambda表达式示例
|
||||
* Lambda表达式是Java 8最重要的新特性之一,它允许把函数作为一个方法的参数
|
||||
*/
|
||||
public static void lambdaExample() {
|
||||
System.out.println("\n=== Lambda表达式示例 ===");
|
||||
|
||||
// 传统的匿名内部类写法
|
||||
Runnable oldRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("传统方式执行Runnable");
|
||||
}
|
||||
};
|
||||
|
||||
// Lambda表达式写法
|
||||
Runnable newRunnable = () -> System.out.println("Lambda方式执行Runnable");
|
||||
|
||||
oldRunnable.run();
|
||||
newRunnable.run();
|
||||
|
||||
// 集合排序的Lambda表达式示例
|
||||
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
|
||||
|
||||
// 传统方式
|
||||
Collections.sort(names, new Comparator<String>() {
|
||||
@Override
|
||||
public int compare(String a, String b) {
|
||||
return a.compareTo(b);
|
||||
}
|
||||
});
|
||||
|
||||
// Lambda方式
|
||||
Collections.sort(names, (a, b) -> a.compareTo(b));
|
||||
|
||||
// 更简洁的Lambda方式
|
||||
names.sort((a, b) -> b.compareTo(a)); // 逆序排列
|
||||
System.out.println("Lambda排序结果: " + names);
|
||||
}
|
||||
}
|
||||
26
demo2/java8-example/src/main/java/Main.java
Normal file
26
demo2/java8-example/src/main/java/Main.java
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* @author maxiaofeng
|
||||
* @date 2025/7/18 10:06
|
||||
*/
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("hello java8.");
|
||||
|
||||
// 1. Lambda表达式示例
|
||||
LambdaExample.lambdaExample();
|
||||
|
||||
// 2. Stream API示例
|
||||
StreamExample.streamExample();
|
||||
|
||||
// 3. Optional示例
|
||||
OptionalExample.optionalExample();
|
||||
|
||||
// 4. 新的日期时间API示例
|
||||
DateTimeExample.dateTimeExample();
|
||||
|
||||
// 5. 函数式接口示例
|
||||
FunctionExample.functionalInterfaceExample();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
35
demo2/java8-example/src/main/java/OptionalExample.java
Normal file
35
demo2/java8-example/src/main/java/OptionalExample.java
Normal file
@@ -0,0 +1,35 @@
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author maxiaofeng
|
||||
* @date 2025/8/5 13:52
|
||||
*/
|
||||
public class OptionalExample {
|
||||
/**
|
||||
* Optional示例
|
||||
* Optional类是一个可以为null的容器对象,用来避免空指针异常
|
||||
*/
|
||||
public static void optionalExample() {
|
||||
System.out.println("\n=== Optional示例 ===");
|
||||
|
||||
// 创建Optional对象
|
||||
Optional<String> optional = Optional.of("Hello Java 8");
|
||||
Optional<String> emptyOptional = Optional.empty();
|
||||
|
||||
// 判断是否有值
|
||||
if (optional.isPresent()) {
|
||||
System.out.println("Optional中的值: " + optional.get());
|
||||
}
|
||||
|
||||
// 使用orElse提供默认值
|
||||
String value = emptyOptional.orElse("默认值");
|
||||
System.out.println("Optional默认值: " + value);
|
||||
|
||||
// 使用ifPresent执行操作
|
||||
optional.ifPresent(s -> System.out.println("处理值: " + s.toUpperCase()));
|
||||
|
||||
// 使用map转换值
|
||||
Optional<String> upperCase = optional.map(String::toUpperCase);
|
||||
upperCase.ifPresent(s -> System.out.println("转换后的值: " + s));
|
||||
}
|
||||
}
|
||||
83
demo2/java8-example/src/main/java/StreamExample.java
Normal file
83
demo2/java8-example/src/main/java/StreamExample.java
Normal file
@@ -0,0 +1,83 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author maxiaofeng
|
||||
* @date 2025/8/5 13:52
|
||||
*/
|
||||
public class StreamExample {
|
||||
|
||||
/**
|
||||
* Stream API示例
|
||||
* Stream API是Java 8中处理集合的关键抽象概念,它可以对集合进行各种操作
|
||||
*/
|
||||
public static void streamExample() {
|
||||
System.out.println("\n=== Stream API示例 ===");
|
||||
|
||||
List<Person> people = Arrays.asList(
|
||||
new Person("Alice", 25),
|
||||
new Person("Bob", 30),
|
||||
new Person("Charlie", 35),
|
||||
new Person("David", 40),
|
||||
new Person("Eve", 20)
|
||||
);
|
||||
|
||||
// 过滤年龄大于25的人
|
||||
List<Person> filtered = people.stream()
|
||||
.filter(person -> person.getAge() > 25)
|
||||
.collect(Collectors.toList());
|
||||
System.out.println("年龄大于25的人: " + filtered);
|
||||
|
||||
// 提取所有人的姓名
|
||||
List<String> names = people.stream()
|
||||
.map(Person::getName)
|
||||
.collect(Collectors.toList());
|
||||
System.out.println("所有人的姓名: " + names);
|
||||
|
||||
// 计算年龄总和
|
||||
int totalAge = people.stream()
|
||||
.mapToInt(Person::getAge)
|
||||
.sum();
|
||||
System.out.println("年龄总和: " + totalAge);
|
||||
|
||||
// 查找第一个年龄大于30的人
|
||||
Optional<Person> person = people.stream()
|
||||
.filter(p -> p.getAge() > 30)
|
||||
.findFirst();
|
||||
person.ifPresent(p -> System.out.println("第一个年龄大于30的人: " + p));
|
||||
|
||||
// 并行流示例
|
||||
long count = people.parallelStream()
|
||||
.filter(p -> p.getAge() > 25)
|
||||
.count();
|
||||
System.out.println("年龄大于25的人数: " + count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 人员实体类
|
||||
*/
|
||||
public static class Person {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person{name='" + name + "', age=" + age + "}";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user