Java 8 十大新特性详解:Lambda、Stream、Optional 一网打尽
引言
Java 8是Java发展史上的一个重要里程碑,引入了众多革命性特性,特别是函数式编程概念的引入,极大地改变了Java的编程范式。本文将详细解析Java 8的十大新特性,包括Lambda表达式、Stream API、Optional类、接口默认方法、方法引用、函数式接口等,通过实际代码示例展示这些特性的强大功能。
Lambda表达式详解
Lambda表达式基础语法
// Lambda表达式基础示例
public class LambdaBasics {
// 函数式接口定义
@FunctionalInterface
public interface Calculator {
int calculate(int a, int b);
}
// 基础Lambda表达式语法
public static void basicSyntax() {
// 传统匿名内部类写法
Calculator traditional = new Calculator() {
@Override
public int calculate(int a, int b) {
return a + b;
}
};
// Lambda表达式写法
Calculator lambda = (int a, int b) -> a + b;
// 简化Lambda表达式(类型推断)
Calculator simplified = (a, b) -> a + b;
// 无参数Lambda
Runnable runnable = () -> System.out.println("Hello from Lambda");
// 单参数Lambda(可省略括号)
Function<String, Integer> stringToInt = s -> s.length();
// 多语句Lambda(需要大括号)
Consumer<String> multiStatement = (str) -> {
System.out.println("Processing: " + str);
System.out.println("Length: " + str.length());
};
// 测试各种写法
System.out.println("Traditional: " + traditional.calculate(5, 3));
System.out.println("Lambda: " + lambda.calculate(5, 3));
System.out.println("Simplified: " + simplified.calculate(5, 3));
runnable.run();
System.out.println("String length: " + stringToInt.apply("Hello"));
multiStatement.accept("Test String");
}
// Lambda表达式类型推断
public static void typeInference() {
// 编译器自动推断函数式接口类型
Predicate<String> isLong = str -> str.length() > 10;
Function<Integer, String> intToString = num -> "Number: " + num;
BiFunction<String, String, String> concat = (s1, s2) -> s1 + s2;
System.out.println("Is 'VeryLongString' long? " + isLong.test("VeryLongString"));
System.out.println("Int to string: " + intToString.apply(42));
System.out.println("Concatenated: " + concat.apply("Hello", " World"));
}
// Lambda表达式变量捕获
public static void variableCapture() {
int multiplier = 10; // 有效的final变量
// Lambda可以捕获局部变量
Function<Integer, Integer> multiply = x -> x * multiplier;
// Lambda可以访问实例变量和静态变量
staticVar = 100;
instanceVar = 200;
Function<Integer, Integer> useStatic = x -> x + staticVar;
Function<Integer, Integer> useInstance = x -> x + instanceVar;
System.out.println("Multiply result: " + multiply.apply(5));
System.out.println("Static var result: " + useStatic.apply(10));
System.out.println("Instance var result: " + useInstance.apply(15));
}
private static int staticVar;
private int instanceVar;
}
Lambda表达式高级应用
// Lambda表达式高级应用示例
public class LambdaAdvanced {
// 函数组合
public static void functionComposition() {
Function<Integer, Integer> add5 = x -> x + 5;
Function<Integer, Integer> multiplyBy2 = x -> x * 2;
// 先加5再乘2
Function<Integer, Integer> add5ThenMultiplyBy2 = add5.andThen(multiplyBy2);
// 先乘2再加5
Function<Integer, Integer> multiplyBy2ThenAdd5 = add5.compose(multiplyBy2);
System.out.println("add5ThenMultiplyBy2(10): " + add5ThenMultiplyBy2.apply(10)); // 30
System.out.println("multiplyBy2ThenAdd5(10): " + multiplyBy2ThenAdd5.apply(10)); // 25
}
// 高阶函数
public static void higherOrderFunctions() {
// 返回函数的函数
Function<Integer, Function<Integer, Integer>> createMultiplier =
factor -> value -> value * factor;
Function<Integer, Integer> multiplyBy3 = createMultiplier.apply(3);
Function<Integer, Integer> multiplyBy5 = createMultiplier.apply(5);
System.out.println("Multiply by 3: " + multiplyBy3.apply(10)); // 30
System.out.println("Multiply by 5: " + multiplyBy5.apply(10)); // 50
// 接受函数作为参数的函数
BiFunction<Integer, Function<Integer, Integer>, Integer> applyAndDouble =
(value, func) -> func.apply(value) * 2;
System.out.println("Apply and double: " +
applyAndDouble.apply(5, x -> x + 10)); // 30
}
// 条件逻辑Lambda
public static void conditionalLogic() {
BiFunction<Integer, Integer, String> compareNumbers = (a, b) -> {
if (a > b) return a + " is greater than " + b;
else if (a < b) return a + " is less than " + b;
else return a + " equals " + b;
};
Predicate<Integer> isEven = num -> num % 2 == 0;
Predicate<Integer> isPositive = num -> num > 0;
// 组合条件
Predicate<Integer> isEvenAndPositive = isEven.and(isPositive);
System.out.println(compareNumbers.apply(10, 5));
System.out.println("Is 4 even? " + isEven.test(4));
System.out.println("Is -3 positive? " + isPositive.test(-3));
System.out.println("Is 4 even and positive? " + isEvenAndPositive.test(4));
}
// 异常处理在Lambda中
public static void exceptionHandling() {
// Lambda中处理异常
Function<String, Integer> parseIntSafe = str -> {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + str);
return 0;
}
};
System.out.println("Parse '123': " + parseIntSafe.apply("123"));
System.out.println("Parse 'abc': " + parseIntSafe.apply("abc"));
}
}
Stream API详解
Stream基础概念
// Stream API基础示例
public class StreamBasics {
// 创建Stream的多种方式
public static void streamCreation() {
// 从集合创建Stream
List<String> list = Arrays.asList("apple", "banana", "cherry");
Stream<String> listStream = list.stream();
// 从数组创建Stream
String[] array = {
"dog", "cat", "bird"};
Stream<String> arrayStream = Arrays.stream(array);
// 使用Stream.of()创建
Stream<String> ofStream = Stream.of("red", "green", "blue");
// 使用Stream.builder()创建
Stream<String> builderStream = Stream.<String>builder()
.add("one")
.add("two")
.add("three")
.build();
// 无限Stream
Stream<Double> randomStream = Stream.generate(Math::random);
Stream<Integer> iterateStream = Stream.iterate(0, n -> n + 1);
// 打印示例
System.out.println("List stream: ");
listStream.forEach(System.out::println);
System.out.println("Array stream: ");
arrayStream.forEach(System.out::println);
System.out.println("Of stream: ");
ofStream.forEach(System.out::println);
}
// Stream中间操作
public static void intermediateOperations() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// filter: 过滤操作
Stream<Integer> filtered = numbers.stream()
.filter(n -> n % 2 == 0);
// map: 转换操作
Stream<String> mapped = numbers.stream()
.map(n -> "Number: " + n);
// flatMap: 扁平化操作
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d", "e"),
Arrays.asList("f")
);
Stream<String> flatMapped = nestedList.stream()
.flatMap(List::stream);
// distinct: 去重操作
List<Integer> withDuplicates = Arrays.asList(1, 2, 2, 3, 3, 3, 4);
Stream<Integer> distinct = withDuplicates.stream()
.distinct();
// sorted: 排序操作
Stream<Integer> sorted = numbers.stream()
.sorted((a, b) -> b.compareTo(a)); // 降序
// limit: 限制操作
Stream<Integer> limited = numbers.stream()
.limit(3);
// skip: 跳过操作
Stream<Integer> skipped = numbers.stream()
.skip(5);
// 演示结果
System.out.println("Filtered (even numbers): ");
filtered.forEach(n -> System.out.print(n + " "));
System.out.println();
System.out.println("Mapped: ");
mapped.forEach(System.out::println);
System.out.println("FlatMapped: ");
flatMapped.forEach(System.out::print);
System.out.println();
System.out.println("Distinct: ");
distinct.forEach(n -> System.out.print(n + " "));
System.out.println();
System.out.println("Sorted (descending): ");
sorted.forEach(n -> System.out.print(n + " "));
System.out.println();
System.out.println("Limited (first 3): ");
limited.forEach(n -> System.out.print(n + " "));
System.out.println();
System.out.println("Skipped (after 5): ");
skipped.forEach(n -> System.out.print(n + " "));
System.out.println();
}
// Stream终端操作
public static void terminalOperations() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// collect: 收集到集合
List<Integer> collected = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// reduce: 归约操作
Optional<Integer> sum = numbers.stream()
.reduce((a, b) -> a + b);
Integer sumWithIdentity = numbers.stream()
.reduce(0, Integer::sum);
// count: 计数操作
long count = numbers.stream()
.filter(n -> n > 5)
.count();
// anyMatch, allMatch, noneMatch: 匹配操作
boolean anyEven = numbers.stream()
.anyMatch(n -> n % 2 == 0);
boolean allPositive = numbers.stream()
.allMatch(n -> n > 0);
boolean noneNegative = numbers.stream()
.noneMatch(n -> n < 0);
// findFirst, findAny: 查找操作
Optional<Integer> firstEven = numbers.stream()
.filter(n -> n % 2 == 0)
.findFirst();
Optional<Integer> anyEvenNumber = numbers.stream()
.filter(n -> n % 2 == 0)
.findAny();
// forEach: 遍历操作
System.out.println("ForEach example: ");
numbers.stream()
.filter(n -> n % 3 == 0)
.forEach(System.out::println);
// 打印结果
System.out.println("Collected even numbers: " + collected);
System.out.println("Sum (with Optional): " + sum.orElse(0));
System.out.println("Sum (with identity): " + sumWithIdentity);
System.out.println("Count of numbers > 5: " + count);
System.out.println("Any even number exists: " + anyEven);
System.out.println("All numbers positive: " + allPositive);
System.out.println("No negative numbers: " + noneNegative);
System.out.println("First even number: " + firstEven.orElse(-1));
System.out.println("Any even number: " + anyEvenNumber.orElse(-1));
}
}
Stream高级应用
// Stream API高级应用示例
public class StreamAdvanced {
// 并行Stream
public static void parallelStream() {
List<Integer> numbers = IntStream.rangeClosed(1, 1000000)
.boxed()
.collect(Collectors.toList());
long startTime = System.currentTimeMillis();
// 串行Stream
long serialSum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToLong(n -> (long) n * n)
.sum();
long serialTime = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
// 并行Stream
long parallelSum = numbers.parallelStream()
.filter(n -> n % 2 == 0)
.mapToLong(n -> (long) n * n)
.sum();
long parallelTime = System.currentTimeMillis() - startTime;
System.out.println("Serial processing time: " + serialTime + "ms");
System.out.println("Parallel processing time: " + parallelTime + "ms");
System.out.println("Results match: " + (serialSum == parallelSum));
}
// 分组和分区
public static void groupingAndPartitioning() {
List<Person> people = Arrays.asList(
new Person("Alice", 25, "Engineer"),
new Person("Bob", 30, "Manager"),
new Person("Charlie", 25, "Engineer"),
new Person("Diana", 28, "Designer"),
new Person("Eve", 35, "Manager")
);
// 按职业分组
Map<String, List<Person>> byRole = people.stream()
.collect(Collectors.groupingBy(Person::getRole));
// 按年龄分组
Map<Integer, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 多级分组
Map<String, Map<Integer, List<Person>>> byRoleAndAge = people.stream()
.collect(Collectors.groupingBy(Person::getRole,
Collectors.groupingBy(Person::getAge)));
// 分区(按条件分为两组)
Map<Boolean, List<Person>> byAgePartition = people.stream()
.collect(Collectors.partitioningBy(p -> p.getAge() > 30));
// 统计信息
Map<String, Long> roleCount = people.stream()
.collect(Collectors.groupingBy(Person::getRole,
Collectors.counting()));
// 打印结果
System.out.println("Grouped by role: " + byRole);
System.out.println("Grouped by age: " + byAge);
System.out.println("Grouped by role and age: " + byRoleAndAge);
System.out.println("Partitioned by age > 30: " + byAgePartition);
System.out.println("Role count: " + roleCount);
}
// 归约和收集高级操作
public static void reductionAndCollectionAdvanced() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 自定义收集器
Collector<Integer, ?, String> joiningCollector = Collectors.joining(", ", "[", "]");
String joined = numbers.stream()
.map(String::valueOf)
.collect(joiningCollector);
// 统计信息
IntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
// 字符串连接
String concatenated = numbers.stream()
.map(String::valueOf)
.collect(Collectors.joining(" - "));
// 最大值和最小值
Optional<Integer> max = numbers.stream()
.max(Integer::compareTo);
Optional<Integer> min = numbers.stream()
.min(Integer::compareTo);
// 自定义归约
String customReduction = numbers.stream()
.map(String::valueOf)
.reduce("", (s1, s2) -> s1.isEmpty() ? s2 : s1 + ", " + s2);
// 打印结果
System.out.println("Joined with custom collector: " + joined);
System.out.println("Statistics: " + stats);
System.out.println("Concatenated: " + concatenated);
System.out.println("Max: " + max.orElse(-1));
System.out.println("Min: " + min.orElse(-1));
System.out.println("Custom reduction: " + customReduction);
}
// 流的短路操作
public static void shortCircuitOperations() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// findFirst - 短路操作
Optional<Integer> firstEven = numbers.stream()
.filter(n -> {
System.out.println("Checking: " + n);
return n % 2 == 0;
})
.findFirst();
System.out.println("First even number: " + firstEven.orElse(-1));
// anyMatch - 短路操作
boolean hasLargeNumber = numbers.stream()
.map(n -> {
System.out.println("Processing: " + n);
return n;
})
.anyMatch(n -> n > 5);
System.out.println("Has number > 5: " + hasLargeNumber);
// limit - 短路操作
List<Integer> limited = numbers.stream()
.map(n -> {
System.out.println("Mapping: " + n);
return n * 2;
})
.limit(3)
.collect(Collectors.toList());
System.out.println("Limited result: " + limited);
}
}
// 人员类用于Stream示例
class Person {
private String name;
private int age;
private String role;
public Person(String name, int age, String role) {
this.name = name;
this.age = age;
this.role = role;
}
public String getName() {
return name; }
public int getAge() {
return age; }
public String getRole() {
return role; }
@Override
public String toString() {
return String.format("Person{name='%s', age=%d, role='%s'}", name, age, role);
}
}
Optional类详解
Optional基础用法
// Optional类基础示例
public class OptionalBasics {
// Optional创建方法
public static void optionalCreation() {
// 创建空的Optional
Optional<String> emptyOpt = Optional.empty();
// 创建包含值的Optional
Optional<String> valueOpt = Optional.of("Hello");
// 创建可能为null的Optional
Optional<String> nullableOpt = Optional.ofNullable(null);
Optional<String> nonNullOpt = Optional.ofNullable("World");
System.out.println("Empty Optional: " + emptyOpt);
System.out.println("Value Optional: " + valueOpt);
System.out.println("Nullable (null): " + nullableOpt);
System.out.println("Nullable (non-null): " + nonNullOpt);
}
// Optional常用方法
public static void optionalMethods() {
Optional<String> presentOpt = Optional.of("Present Value");
Optional<String> emptyOpt = Optional.empty();
// isPresent() - 检查是否有值
System.out.println("Present opt is present: " + presentOpt.isPresent());
System.out.println("Empty opt is present: " + emptyOpt.isPresent());
// get() - 获取值(不安全)
if (presentOpt.isPresent()) {
System.out.println("Value: " + presentOpt.get());
}
// orElse() - 提供默认值
String value = presentOpt.orElse("Default Value");
String emptyValue = emptyOpt.orElse("Default Value");
System.out.println("Present value: " + value);
System.out.println("Empty value with default: " + emptyValue);
// orElseGet() - 提供默认值工厂
String lazyValue = emptyOpt.orElseGet(() -> {
System.out.println("Computing default value...");
return "Lazy Default";
});
System.out.println("Lazy default value: " + lazyValue);
// orElseThrow() - 提供异常
try {
String throwValue = emptyOpt.orElseThrow(() ->
new RuntimeException("Value not present"));
} catch (RuntimeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
// ifPresent() - 有值时执行操作
presentOpt.ifPresent(value1 -> System.out.println("Value present: " + value1));
emptyOpt.ifPresent(value1 -> System.out.println("This won't print"));
}
// Optional链式操作
public static void optionalChaining() {
// map() - 转换Optional中的值
Optional<String> opt = Optional.of("Hello");
Optional<Integer> lengthOpt = opt.map(String::length);
System.out.println("Original: " + opt);
System.out.println("Length: " + lengthOpt);
// flatMap() - 避免Optional嵌套
Optional<String> upperOpt = opt.flatMap(s ->
Optional.of(s.toUpperCase()));
System.out.println("Uppercase: " + upperOpt);
// filter() - 过滤Optional
Optional<String> filteredOpt = opt.filter(s -> s.length() > 3);
Optional<String> filteredEmpty = opt.filter(s -> s.length() < 3);
System.out.println("Filtered (length > 3): " + filteredOpt);
System.out.println("Filtered (length < 3): " + filteredEmpty);
}
// Optional实际应用示例
public static void practicalExamples() {
// 模拟可能返回null的方法
UserService userService = new UserService();
// 传统null检查
User user1 = userService.findUser("123");
if (user1 != null) {
String name = user1.getName();
if (name != null) {
System.out.println("User name: " + name.toUpperCase());
}
}
// 使用Optional的改进版本
Optional<User> userOpt = userService.findUserOptional("123");
userOpt
.map(User::getName)
.filter(name -> name.length() > 0)
.map(String::toUpperCase)
.ifPresent(name -> System.out.println("User name: " + name));
// 处理不存在的情况
Optional<User> nonExistent = userService.findUserOptional("999");
String result = nonExistent
.map(User::getName)
.orElse("Unknown User");
System.out.println("Result for non-existent user: " + result);
}
}
// 用户服务类
class UserService {
private Map<String, User> users = new HashMap<>();
public UserService() {
users.put("123", new User("123", "John Doe", "john@example.com"));
users.put("456", new User("456", "Jane Smith", "jane@example.com"));
}
// 传统方法,可能返回null
public User findUser(String id) {
return users.get(id);
}
// 返回Optional的方法
public Optional<User> findUserOptional(String id) {
return Optional.ofNullable(users.get(id));
}
}
// 用户类
class User {
private String id;
private String name;
private String email;
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id; }
public String getName() {
return name; }
public String getEmail() {
return email; }
@Override
public String toString() {
return String.format("User{id='%s', name='%s', email='%s'}", id, name, email);
}
}
Optional高级应用
// Optional高级应用示例
public class OptionalAdvanced {
// Optional与Stream结合
public static void optionalWithStream() {
List<Optional<String>> optionalList = Arrays.asList(
Optional.of("Hello"),
Optional.empty(),
Optional.of("World"),
Optional.empty(),
Optional.of("Java")
);
// 过滤出有值的Optional并收集
List<String> values = optionalList.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
System.out.println("Filtered values: " + values);
// 使用Optional.stream() (Java 9+)
// 在Java 8中,我们可以手动实现类似功能
List<String> flatValues = optionalList.stream()
.flatMap(opt -> opt.map(Stream::of).orElse(Stream.empty()))
.collect(Collectors.toList());
System.out.println("Flat values: " + flatValues);
}
// Optional异常处理
public static void optionalExceptionHandling() {
// 安全的字符串解析
Function<String, Optional<Integer>> safeParse = str -> {
try {
return Optional.of(Integer.parseInt(str));
} catch (NumberFormatException e) {
return Optional.empty();
}
};
List<String> numbers = Arrays.asList("123", "abc", "456", "def", "789");
List<Integer> parsed = numbers.stream()
.map(safeParse)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
System.out.println("Parsed numbers: " + parsed);
// 链式安全操作
Optional<String> result = Optional.of("123")
.flatMap(s -> safeParse.apply(s))
.filter(n -> n > 100)
.map(n -> n * 2)
.map(String::valueOf);
System.out.println("Chained result: " + result.orElse("No result"));
}
// Optional在数据处理中的应用
public static void optionalDataProcessing() {
List<Person> people = Arrays.asList(
new Person("Alice", 25, "Engineer"),
new Person("Bob", 30, "Manager"),
new Person("Charlie", 25, "Designer"),
new Person("Diana", 28, "Engineer")
);
// 查找年龄最大的工程师
Optional<Person> seniorEngineer = people.stream()
.filter(p -> "Engineer".equals(p.getRole()))
.max(Comparator.comparingInt(Person::getAge));
String result = seniorEngineer
.map(p -> p.getName() + " is the senior engineer")
.orElse("No engineers found");
System.out.println(result);
// 计算平均年龄
OptionalDouble avgAge = people.stream()
.mapToInt(Person::getAge)
.average();
String avgResult = avgAge.isPresent() ?
"Average age: " + avgAge.getAsDouble() :
"Cannot calculate average";
System.out.println(avgResult);
}
// Optional与方法引用结合
public static void optionalMethodReferences() {
// 使用方法引用简化Optional操作
Optional<String> opt = Optional.of("hello world");
// 转换为大写
String upper = opt.map(String::toUpperCase).orElse("");
System.out.println("Uppercase: " + upper);
// 获取长度
int length = opt.map(String::length).orElse(0);
System.out.println("Length: " + length);
// 分割字符串
List<String> parts = opt
.map(s -> s.split(" "))
.map(Arrays::asList)
.orElse(Collections.emptyList());
System.out.println("Parts: " + parts);
}
}
函数式接口详解
内置函数式接口
// 内置函数式接口示例
public class FunctionalInterfaces {
// Predicate接口示例
public static void predicateExamples() {
// Predicate<T>: 接受一个参数,返回boolean
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositive = n -> n > 0;
System.out.println("Is 4 even? " + isEven.test(4));
System.out.println("Is -3 positive? " + isPositive.test(-3));
// 组合Predicate
Predicate<Integer> isEvenAndPositive = isEven.and(isPositive);
Predicate<Integer> isEvenOrNegative = isEven.or(n -> n < 0);
Predicate<Integer> isNotEven = isEven.negate();
System.out.println("Is 4 even and positive? " + isEvenAndPositive.test(4));
System.out.println("Is -2 even or negative? " + isEvenOrNegative.test(-2));
System.out.println("Is 4 not even? " + isNotEven.test(4));
// 其他Predicate变体
IntPredicate intPredicate = n -> n > 0;
LongPredicate longPredicate = n -> n < 0;
DoublePredicate doublePredicate = n -> n == 0.0;
}
// Function接口示例
public static void functionExamples() {
// Function<T, R>: 接受一个参数,返回一个结果
Function<String, Integer> stringToInt = String::length;
Function<Integer, String> intToString = n -> "Number: " + n;
System.out.println("Length of 'Hello': " + stringToInt.apply("Hello"));
System.out.println("Int to string: " + intToString.apply(42));
// Function组合
Function<String, String> lengthToString = stringToInt.andThen(n -> "Length: " + n);
Function<String, Integer> prefixLength = stringToInt.compose(s -> "Prefix: " + s);
System.out.println("Length to string: " + lengthToString.apply("Test"));
System.out.println("Prefix length: " + prefixLength.apply("Hello"));
// 其他Function变体
IntFunction<String> intToStringFunc = n -> "Value: " + n;
ToIntFunction<String> stringToIntFunc = String::length;
IntToLongFunction intToLong = n -> (long) n * 2;
}
// Consumer接口示例
public static void consumerExamples() {
// Consumer<T>: 接受一个参数,无返回值
Consumer<String> printConsumer = System.out::println;
Consumer<String> uppercaseConsumer = s -> System.out.println(s.toUpperCase());
printConsumer.accept("Hello Consumer");
uppercaseConsumer.accept("hello consumer");
// Consumer组合
Consumer<String> combinedConsumer = printConsumer.andThen(uppercaseConsumer);
combinedConsumer.accept("Combined");
// 其他Consumer变体
IntConsumer intConsumer = n -> System.out.println("Integer: " + n);
LongConsumer longConsumer = n -> System.out.println("Long: " + n);
DoubleConsumer doubleConsumer = n -> System.out.println("Double: " + n);
intConsumer.accept(42);
longConsumer.accept(100L);
doubleConsumer.accept(3.14);
}
// Supplier接口示例
public static void supplierExamples() {
// Supplier<T>: 无参数,返回一个结果
Supplier<String> stringSupplier = () -> "Supplied String";
Supplier<Integer> randomSupplier = () -> (int) (Math.random() * 100);
Supplier<Date> dateSupplier = Date::new;
System.out.println("Supplied string: " + stringSupplier.get());
System.out.println("Random number: " + randomSupplier.get());
System.out.println("Current date: " + dateSupplier.get());
// Supplier用于延迟计算
Supplier<String> expensiveOperation = () -> {
System.out.println("Performing expensive operation...");
return "Expensive result";
};
// Supplier只在需要时才执行
if (Math.random() > 0.5) {
System.out.println("Result: " + expensiveOperation.get());
} else {
System.out.println("Not executing expensive operation");
}
// 其他Supplier变体
BooleanSupplier booleanSupplier = () -> Math.random() > 0.5;
IntSupplier intSupplier = () -> (int) (Math.random() * 100);
LongSupplier longSupplier = () -> System.currentTimeMillis();
DoubleSupplier doubleSupplier = Math::random;
}
// BiFunction接口示例
public static void biFunctionExamples() {
// BiFunction<T, U, R>: 接受两个参数,返回一个结果
BiFunction<Integer, Integer, Integer> add = Integer::sum;
BiFunction<String, String, String> concatenate = String::concat;
System.out.println("Add result: " + add.apply(5, 3));
System.out.println("Concat result: " + concatenate.apply("Hello", " World"));
// BinaryOperator: BiFunction的特化版本,参数和返回类型相同
BinaryOperator<Integer> multiply = (a, b) -> a * b;
BinaryOperator<String> stringMax = BinaryOperator.maxBy(String::compareTo);
System.out.println("Multiply result: " + multiply.apply(4, 6));
System.out.println("Max string: " + stringMax.apply("apple", "banana"));
}
}
自定义函数式接口
// 自定义函数式接口示例
public class CustomFunctionalInterfaces {
// 自定义函数式接口
@FunctionalInterface
public interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
// 可以有默认方法
default TriFunction<T, U, V, R> andThen(Function<R, R> after) {
return (t, u, v) -> after.apply(apply(t, u, v));
}
}
// 带异常的函数式接口
@FunctionalInterface
public interface ThrowingFunction<T, R> {
R apply(T t) throws Exception;
// 便利方法来处理异常
static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {
return t -> {
try {
return f.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
// 自定义谓词接口
@FunctionalInterface
public interface MultiPredicate<T> {
boolean test(T t);
default MultiPredicate<T> and(MultiPredicate<T> other) {
return t -> this.test(t) && other.test(t);
}
default MultiPredicate<T> or(MultiPredicate<T> other) {
return t -> this.test(t) || other.test(t);
}
default MultiPredicate<T> negate() {
return t -> !this.test(t);
}
}
// 自定义消费者接口
@FunctionalInterface
public interface MultiConsumer<T, U> {
void accept(T t, U u);
default MultiConsumer<T, U> andThen(MultiConsumer<T, U> after) {
return (t, u) -> {
accept(t, u);
after.accept(t, u);
};
}
}
// 演示自定义函数式接口的使用
public static void demonstrateCustomInterfaces() {
// 使用自定义TriFunction
TriFunction<Integer, Integer, Integer, Integer> sumThree = (a, b, c) -> a + b + c;
TriFunction<Integer, Integer, Integer, Integer> sumThreeDoubled =
sumThree.andThen(result -> result * 2);
System.out.println("Sum three: " + sumThree.apply(1, 2, 3));
System.out.println("Sum three doubled: " + sumThreeDoubled.apply(1, 2, 3));
// 使用带异常的函数式接口
ThrowingFunction<String, Integer> parseInteger = Integer::parseInt;
Function<String, Integer> safeParse = ThrowingFunction.unchecked(parseInteger);
System.out.println("Parsed integer: " + safeParse.apply("123"));
// 使用自定义谓词
MultiPredicate<String> isLong = s -> s.length() > 5;
MultiPredicate<String> hasVowel = s -> s.toLowerCase().matches(".*[aeiou].*");
MultiPredicate<String> isLongAndHasVowel = isLong.and(hasVowel);
System.out.println("Is 'Hello' long and has vowel? " +
isLongAndHasVowel.test("Hello"));
System.out.println("Is 'Programming' long and has vowel? " +
isLongAndHasVowel.test("Programming"));
// 使用自定义消费者
MultiConsumer<String, Integer> printBoth = (s, i) ->
System.out.println("String: " + s + ", Integer: " + i);
MultiConsumer<String, Integer> printLength = (s, i) ->
System.out.println("Length: " + s.length());
MultiConsumer<String, Integer> combinedConsumer =
printBoth.andThen(printLength);
combinedConsumer.accept("Hello", 42);
}
}
方法引用详解
方法引用类型
// 方法引用示例
public class MethodReferences {
// 静态方法引用
public static void staticMethodReferences() {
// 相当于 (String s) -> Integer.parseInt(s)
Function<String, Integer> stringToInt = Integer::parseInt;
// 相当于 (String s) -> s.length()
ToIntFunction<String> lengthFunction = String::length;
// 相当于 (a, b) -> Integer.compare(a, b)
Comparator<Integer> intComparator = Integer::compare;
System.out.println("Parsed: " + stringToInt.apply("123"));
System.out.println("Length: " + lengthFunction.applyAsInt("Hello"));
System.out.println("Compare 5 and 3: " + intComparator.compare(5, 3));
}
// 实例方法引用
public static void instanceMethodReferences() {
String str = "Hello World";
// 相当于 () -> str.length()
Supplier<Integer> lengthSupplier = str::length;
// 相当于 (String s) -> str.contains(s)
Predicate<String> containsChecker = str::contains;
System.out.println("Length: " + lengthSupplier.get());
System.out.println("Contains 'World': " + containsChecker.test("World"));
// 更实用的实例方法引用
List<String> words = Arrays.asList("apple", "banana", "cherry");
// 相当于 (String w) -> w.startsWith("a")
words.stream()
.filter("apple"::equals) // 检查是否等于"apple"
.forEach(System.out::println);
}
// 构造方法引用
public static void constructorReferences() {
// 无参构造器引用
Supplier<List<String>> listSupplier = ArrayList::new;
List<String> list = listSupplier.get();
// 有参构造器引用
Function<String, StringBuilder> sbFunction = StringBuilder::new;
StringBuilder sb = sbFunction.apply("Initial text");
// 数组构造器引用
Function<Integer, String[]> arrayFunction = String[]::new;
String[] array = arrayFunction.apply(10);
System.out.println("Created list size: " + list.size());
System.out.println("StringBuilder content: " + sb.toString());
System.out.println("Array length: " + array.length);
}
// 数组方法引用
public static void arrayMethodReferences() {
// 数组的length属性
Function<int[], Integer> arrayLength = arr -> arr.length;
// 或者使用方法引用(不直接支持,但可以通过其他方式)
// 数组元素访问
BiFunction<int[], Integer, Integer> arrayAccess = (arr, index) -> arr[index];
int[] numbers = {
1, 2, 3, 4, 5};
System.out.println("Array length: " + arrayLength.apply(numbers));
System.out.println("Element at index 2: " + arrayAccess.apply(numbers, 2));
}
// 复杂方法引用示例
public static void complexMethodReferences() {
List<String> words = Arrays.asList("hello", "world", "java", "programming");
// 使用方法引用进行排序
words.sort(String::compareToIgnoreCase);
System.out.println("Sorted: " + words);
// 使用方法引用进行转换
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println("Lengths: " + lengths);
// 使用方法引用进行过滤
List<String> longWords = words.stream()
.filter(s -> s.length() > 4)
.collect(Collectors.toList());
System.out.println("Long words: " + longWords);
}
}
接口默认方法详解
默认方法基础
// 接口默认方法示例
public class DefaultMethods {
// 带默认方法的接口
public interface Vehicle {
void start();
// 默认方法
default void stop() {
System.out.println("Vehicle stopped safely");
}
// 另一个默认方法
default void honk() {
System.out.println("Beep beep!");
}
// 静态方法
static void describe() {
System.out.println("This is a vehicle interface");
}
}
// 实现接口的类
public static class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car engine started");
}
// 可以重写默认方法
@Override
public void stop() {
System.out.println("Car brake applied");
Vehicle.super.stop(); // 调用接口的默认实现
}
}
// 另一个实现类
public static class Motorcycle implements Vehicle {
@Override
public void start() {
System.out.println("Motorcycle engine started");
}
}
// 多接口继承示例
public interface Flyable {
default void fly() {
System.out.println("Flying in the sky");
}
}
public interface Swimmable {
default void swim() {
System.out.println("Swimming in water");
}
}
// 类同时实现多个接口
public static class Duck implements Flyable, Swimmable {
// 需要解决默认方法冲突
@Override
public void fly() {
System.out.println("Duck flying");
}
@Override
public void swim() {
System.out.println("Duck swimming");
}
}
// 演示默认方法使用
public static void demonstrateDefaultMethods() {
Vehicle.describe(); // 调用静态方法
Vehicle car = new Car();
car.start();
car.stop();
car.honk();
Vehicle motorcycle = new Motorcycle();
motorcycle.start();
motorcycle.stop();
motorcycle.honk();
Duck duck = new Duck();
duck.fly();
duck.swim();
}
}
默认方法高级应用
// 默认方法高级应用示例
public class DefaultMethodsAdvanced {
// 函数式接口中的默认方法
public interface Calculator {
int calculate(int a, int b);
default int add(int a, int b) {
return calculate(a, b);
}
default int multiply(int a, int b) {
return a * b;
}
default int square(int a) {
return multiply(a, a);
}
// 组合操作
default int calculateAndSquare(int a, int b) {
int result = calculate(a, b);
return square(result);
}
}
// 链式调用默认方法
public interface FluentInterface {
String getValue();
default FluentInterface withPrefix(String prefix) {
return () -> prefix + getValue();
}
default FluentInterface withSuffix(String suffix) {
return () -> getValue() + suffix;
}
default FluentInterface toUpperCase() {
return () -> getValue().toUpperCase();
}
}
public static class SimpleFluent implements FluentInterface {
private final String value;
public SimpleFluent(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
}
// 配置接口
public interface Configurable {
default String getProperty(String key) {
return System.getProperty(key);
}
default String getProperty(String key, String defaultValue) {
String value = getProperty(key);
return value != null ? value : defaultValue;
}
default int getIntProperty(String key, int defaultValue) {
String value = getProperty(key);
try {
return value != null ? Integer.parseInt(value) : defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
default boolean getBooleanProperty(String key, boolean defaultValue) {
String value = getProperty(key);
return value != null ? Boolean.parseBoolean(value) : defaultValue;
}
}
public static class MyService implements Configurable {
public void initialize() {
int port = getIntProperty("server.port", 8080);
boolean debug = getBooleanProperty("debug.enabled", false);
String name = getProperty("app.name", "MyApp");
System.out.println("Initializing service:");
System.out.println(" Port: " + port);
System.out.println(" Debug: " + debug);
System.out.println(" Name: " + name);
}
}
// 演示高级默认方法应用
public static void demonstrateAdvancedDefaultMethods() {
// 计算器示例
Calculator adder = Integer::sum;
System.out.println("Square of (3+4): " + adder.calculateAndSquare(3, 4));
// 链式调用示例
FluentInterface fluent = new SimpleFluent("hello")
.withPrefix("pre_")
.withSuffix("_post")
.toUpperCase();
System.out.println("Fluent result: " + fluent.getValue());
// 配置接口示例
MyService service = new MyService();
service.initialize();
}
}
日期时间API详解
新日期时间API基础
// Java 8日期时间API示例
public class DateTimeAPI {
// LocalDate示例
public static void localDateExamples() {
// 创建LocalDate
LocalDate today = LocalDate.now();
LocalDate specificDate = LocalDate.of(2023, 12, 25);
LocalDate parsedDate = LocalDate.parse("2023-12-25");
System.out.println("Today: " + today);
System.out.println("Christmas: " + specificDate);
System.out.println("Parsed: " + parsedDate);
// 日期计算
LocalDate nextWeek = today.plusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);
LocalDate nextYear = today.plusYears(1);
System.out.println("Next week: " + nextWeek);
System.out.println("Last month: " + lastMonth);
System.out.println("Next year: " + nextYear);
// 日期比较
System.out.println("Today is before Christmas: " + today.isBefore(specificDate));
System.out.println("Today is after Christmas: " + today.isAfter(specificDate));
// 日期字段获取
System.out.println("Day of week: " + today.getDayOfWeek());
System.out.println("Day of month: " + today.getDayOfMonth());
System.out.println("Month: " + today.getMonth());
System.out.println("Year: " + today.getYear());
}
// LocalTime示例
public static void localTimeExamples() {
// 创建LocalTime
LocalTime now = LocalTime.now();
LocalTime specificTime = LocalTime.of(14, 30, 45);
LocalTime parsedTime = LocalTime.parse("14:30:45");
System.out.println("Current time: " + now);
System.out.println("Specific time: " + specificTime);
System.out.println("Parsed time: " + parsedTime);
// 时间计算
LocalTime later = now.plusHours(2);
LocalTime earlier = now.minusMinutes(30);
System.out.println("2 hours later: " + later);
System.out.println("30 minutes earlier: " + earlier);
// 时间字段获取
System.out.println("Hour: " + now.getHour());
System.out.println("Minute: " + now.getMinute());
System.out.println("Second: " + now.getSecond());
}
// LocalDateTime示例
public static void localDateTimeExamples() {
// 创建LocalDateTime
LocalDateTime now = LocalDateTime.now();
LocalDateTime specificDateTime = LocalDateTime.of(2023, 12, 25, 14, 30, 45);
LocalDateTime parsedDateTime = LocalDateTime.parse("2023-12-25T14:30:45");
System.out.println("Current date-time: " + now);
System.out.println("Specific date-time: " + specificDateTime);
System.out.println("Parsed date-time: " + parsedDateTime);
// 日期时间计算
LocalDateTime future = now.plusDays(7).plusHours(3);
LocalDateTime past = now.minusMonths(1).minusHours(5);
System.out.println("1 week and 3 hours later: " + future);
System.out.println("1 month and 5 hours ago: " + past);
// 从LocalDateTime提取日期和时间
LocalDate datePart = now.toLocalDate();
LocalTime timePart = now.toLocalTime();
System.out.println("Date part: " + datePart);
System.out.println("Time part: " + timePart);
}
// ZonedDateTime示例
public static void zonedDateTimeExamples() {
// 创建ZonedDateTime
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime specificZone = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("System default: " + now);
System.out.println("UTC: " + utcTime);
System.out.println("New York: " + specificZone);
// 时区转换
ZonedDateTime tokyoTime = now.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
System.out.println("Tokyo time: " + tokyoTime);
// 从其他日期时间类型创建ZonedDateTime
LocalDateTime localDateTime = LocalDateTime.of(2023, 12, 25, 14, 30);
ZonedDateTime zoned = localDateTime.atZone(ZoneId.systemDefault());
System.out.println("From LocalDateTime: " + zoned);
}
}
日期时间高级操作
// 日期时间高级操作示例
public class DateTimeAdvanced {
// 日期时间格式化
public static void dateTimeFormatting() {
LocalDateTime dateTime = LocalDateTime.now();
// 使用预定义格式
System.out.println("ISO format: " + dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
System.out.println("Basic ISO: " + dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
// 自定义格式
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Custom format: " + dateTime.format(customFormatter));
// 本地化格式
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")
.withLocale(Locale.US);
System.out.println("Localized format: " + dateTime.format(localizedFormatter));
// 解析日期时间字符串
String dateString = "2023-12-25 14:30:45";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsed = LocalDateTime.parse(dateString, parser);
System.out.println("Parsed date-time: " + parsed);
}
// 日期时间计算和比较
public static void dateTimeCalculations() {
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 12, 31);
// 计算日期间隔
Period period = Period.between(startDate, endDate);
System.out.println("Period: " + period.getYears() + " years, " +
period.getMonths() + " months, " +
period.getDays() + " days");
// 计算天数差
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Days between: " + daysBetween);
// 计算工作日(示例)
long businessDays = calculateBusinessDays(startDate, endDate);
System.out.println("Business days: " + businessDays);
// 时间间隔
LocalTime start = LocalTime.of(9, 0);
LocalTime end = LocalTime.of(17, 30);
Duration duration = Duration.between(start, end);
System.out.println("Duration: " + duration.toHours() + " hours, " +
duration.toMinutesPart() + " minutes");
}
// 计算工作日辅助方法
private static long calculateBusinessDays(LocalDate start, LocalDate end) {
long businessDays = 0;
LocalDate current = start;
while (!current.isAfter(end)) {
DayOfWeek dayOfWeek = current.getDayOfWeek();
if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
businessDays++;
}
current = current.plusDays(1);
}
return businessDays;
}
// 日期时间调整器
public static void temporalAdjusters() {
LocalDate date = LocalDate.of(2023, 3, 15);
// 使用内置调整器
LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
LocalDate firstDayOfNextYear = date.with(TemporalAdjusters.firstDayOfNextYear());
System.out.println("Original: " + date);
System.out.println("First day of month: " + firstDayOfMonth);
System.out.println("Last day of month: " + lastDayOfMonth);
System.out.println("Next Monday: " + nextMonday);
System.out.println("First day of next year: " + firstDayOfNextYear);
// 自定义调整器
TemporalAdjuster nextWorkingDay = temporal -> {
LocalDate date1 = LocalDate.from(temporal);
do {
date1 = date1.plusDays(1);
} while (date1.getDayOfWeek() == DayOfWeek.SATURDAY ||
date1.getDayOfWeek() == DayOfWeek.SUNDAY);
return date1;
};
LocalDate nextWorkDay = date.with(nextWorkingDay);
System.out.println("Next working day: " + nextWorkDay);
}
// 日期时间验证和约束
public static void dateTimeValidation() {
// 验证日期是否在范围内
LocalDate date = LocalDate.now();
LocalDate minDate = LocalDate.of(2020, 1, 1);
LocalDate maxDate = LocalDate.of(2025, 12, 31);
boolean isValid = !date.isBefore(minDate) && !date.isAfter(maxDate);
System.out.println("Date is valid: " + isValid);
// 验证时间是否在营业时间内
LocalTime currentTime = LocalTime.now();
LocalTime openTime = LocalTime.of(9, 0);
LocalTime closeTime = LocalTime.of(18, 0);
boolean isOpen = currentTime.isAfter(openTime) && currentTime.isBefore(closeTime);
System.out.println("Business is open: " + isOpen);
// 计算截止日期
LocalDateTime now = LocalDateTime.now();
LocalDateTime deadline = now.plusDays(7).withHour(17).withMinute(0).withSecond(0);
System.out.println("Deadline: " + deadline);
Duration remaining = Duration.between(now, deadline);
System.out.println("Time remaining: " + remaining.toDays() + " days, " +
remaining.toHoursPart() + " hours");
}
}
Nashorn JavaScript引擎
Nashorn基础用法
// Nashorn JavaScript引擎示例
public class NashornExample {
// 基本JavaScript执行
public static void basicJavaScriptExecution() {
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
// 执行简单JavaScript代码
engine.eval("print('Hello from JavaScript!')");
// 执行JavaScript表达式
Object result = engine.eval("3 + 4 * 2");
System.out.println("JavaScript result: " + result);
// 定义JavaScript函数
engine.eval("function greet(name) { return 'Hello, ' + name + '!'; }");
// 调用JavaScript函数
Invocable invocable = (Invocable) engine;
Object greeting = invocable.invokeFunction("greet", "Java");
System.out.println("Greeting: " + greeting);
} catch (ScriptException | NoSuchMethodException e) {
e.printStackTrace();
}
}
// Java对象与JavaScript交互
public static void javaJavaScriptInteraction() {
try {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// 将Java对象传递给JavaScript
Person person = new Person("John", 30, "Engineer");
engine.put("person", person);
// JavaScript访问Java对象
engine.eval("print('Name: ' + person.getName())");
engine.eval("print('Age: ' + person.getAge())");
engine.eval("print('Role: ' + person.getRole())");
// 创建Java对象
engine.eval("var ArrayList = Java.type('java.util.ArrayList');");
engine.eval("var list = new ArrayList();");
engine.eval("list.add('Hello');");
engine.eval("list.add('World');");
engine.eval("print('List size: ' + list.size());");
// 获取JavaScript结果
Object listObj = engine.get("list");
System.out.println("Java list: " + listObj);
} catch (ScriptException e) {
e.printStackTrace();
}
}
// JavaScript函数返回Java对象
public static void javascriptFunctionReturnsJavaObject() {
try {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// 定义返回Java对象的JavaScript函数
engine.eval(
"function createPerson(name, age) {" +
" var Person = Java.type('DateTimeAdvanced$Person');" +
" return new Person(name, age, 'Developer');" +
"}"
);
Invocable invocable = (Invocable) engine;
Object personObj = invocable.invokeFunction("createPerson", "Alice", 25);
if (personObj instanceof Person) {
Person person = (Person) personObj;
System.out.println("Created person: " + person);
}
} catch (ScriptException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
Base64编码
Base64编码示例
// Base64编码示例
public class Base64Example {
// Base64基本编码解码
public static void base64Basic() {
String originalString = "Hello, World! This is a test string.";
System.out.println("Original: " + originalString);
// 编码
String encoded = Base64.getEncoder().encodeToString(originalString.getBytes());
System.out.println("Encoded: " + encoded);
// 解码
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes);
System.out.println("Decoded: " + decoded);
// 验证编码解码是否正确
System.out.println("Encoding/Decoding successful: " + originalString.equals(decoded));
}
// Base64 URL安全编码
public static void base64UrlSafe() {
String url = "https://example.com/api?param=value&other=123";
System.out.println("Original URL: " + url);
// URL安全编码(使用-和_代替+和/)
String urlSafeEncoded = Base64.getUrlEncoder().encodeToString(url.getBytes());
System.out.println("URL safe encoded: " + urlSafeEncoded);
// 解码URL安全编码
byte[] urlSafeDecoded = Base64.getUrlDecoder().decode(urlSafeEncoded);
String urlSafeDecodedStr = new String(urlSafeDecoded);
System.out.println("URL safe decoded: " + urlSafeDecodedStr);
}
// Base64 MIME编码
public static void base64Mime() {
// 创建一个较长的字符串来演示MIME编码的换行
StringBuilder longText = new StringBuilder();
for (int i = 0; i < 100; i++) {
longText.append("This is line ").append(i).append(" of a long text. ");
}
String longString = longText.toString();
// MIME编码(每76个字符换行)
String mimeEncoded = Base64.getMimeEncoder().encodeToString(longString.getBytes());
System.out.println("MIME encoded (first 100 chars): " +
mimeEncoded.substring(0, Math.min(100, mimeEncoded.length())));
// 解码MIME编码
byte[] mimeDecoded = Base64.getMimeDecoder().decode(mimeEncoded);
String mimeDecodedStr = new String(mimeDecoded);
System.out.println("MIME decoded matches: " + longString.equals(mimeDecodedStr));
}
// Base64实际应用示例
public static void base64PracticalApplications() {
// 1. 编码图片数据(概念演示)
String imageData = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
try {
byte[] imageBytes = Base64.getDecoder().decode(imageData);
System.out.println("Image data decoded, length: " + imageBytes.length);
} catch (IllegalArgumentException e) {
System.out.println("Invalid Base64 string");
}
// 2. HTTP基本认证编码
String credentials = "username:password";
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
System.out.println("Basic Auth header: " + basicAuth);
// 3. 编码JSON数据
String jsonData = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
String encodedJson = Base64.getEncoder().encodeToString(jsonData.getBytes());
System.out.println("Encoded JSON: " + encodedJson);
// 4. 生成安全的随机token
SecureRandom random = new SecureRandom();
byte[] tokenBytes = new byte[32]; // 256 bits
random.nextBytes(tokenBytes);
String secureToken = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
System.out.println("Secure token: " + secureToken);
}
}
重复注解
重复注解示例
// 重复注解示例
public class RepeatableAnnotations {
// 定义可重复的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(Author.List.class)
public @interface Author {
String name();
String role() default "Developer";
// 包含重复注解的容器注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface List {
Author[] value();
}
}
// 另一个可重复注解示例
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(Permission.List.class)
public @interface Permission {
String value();
String description() default "";
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface List {
Permission[] value();
}
}
// 使用重复注解
@Permission(value = "READ", description = "Read access")
@Permission(value = "WRITE", description = "Write access")
@Permission(value = "DELETE", description = "Delete access")
public static class SecureResource {
@Author(name = "John Doe", role = "Lead Developer")
@Author(name = "Jane Smith", role = "Senior Developer")
@Author(name = "Bob Johnson", role = "QA Engineer")
public void processData() {
System.out.println("Processing data...");
}
@Author(name = "Alice Brown")
public void validateInput() {
System.out.println("Validating input...");
}
}
// 读取重复注解
public static void readRepeatableAnnotations() {
Class<SecureResource> clazz = SecureResource.class;
// 读取类型级别的重复注解
Permission[] permissions = clazz.getAnnotationsByType(Permission.class);
System.out.println("Permissions for " + clazz.getSimpleName() + ":");
for (Permission perm : permissions) {
System.out.println(" " + perm.value() + ": " + perm.description());
}
// 读取方法级别的重复注解
try {
Method processDataMethod = clazz.getMethod("processData");
Author[] authors = processDataMethod.getAnnotationsByType(Author.class);
System.out.println("\nAuthors for processData method:");
for (Author author : authors) {
System.out.println(" " + author.name() + " (" + author.role() + ")");
}
Method validateInputMethod = clazz.getMethod("validateInput");
Author[] validateAuthors = validateInputMethod.getAnnotationsByType(Author.class);
System.out.println("\nAuthors for validateInput method:");
for (Author author : validateAuthors) {
System.out.println(" " + author.name() + " (" + author.role() + ")");
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
总结与特性对比
Java 8新特性对比表格
| 特性 | 主要用途 | 优势 | 使用场景 |
|---|---|---|---|
| Lambda表达式 | 简化匿名内部类 | 代码简洁,函数式编程 | 事件处理,集合操作 |
| Stream API | 集合数据处理 | 声明式编程,链式操作 | 数据过滤,转换,聚合 |
| Optional | 避免空指针异常 | 类型安全,明确意图 | 返回值处理,链式调用 |
| 接口默认方法 | 向后兼容的接口扩展 | 无需修改实现类 | API版本升级 |
| 方法引用 | 简化Lambda表达式 | 更简洁的语法 | 已有方法的函数式使用 |
| 函数式接口 | 函数式编程基础 | 类型安全,性能优化 | Lambda表达式支持 |
| 日期时间API | 日期时间处理 | 线程安全,设计合理 | 时间计算,格式化 |
| Nashorn | JavaScript执行 | 高性能,Java集成 | 脚本引擎,混合编程 |
| Base64 | 编码解码 | 标准实现,多种格式 | 数据传输,认证 |
| 重复注解 | 多个相同注解 | 语义清晰,使用方便 | 权限控制,作者信息 |
// 综合示例:使用多个Java 8特性
public class Java8FeaturesIntegration {
// 综合使用多个Java 8特性
public static void integratedExample() {
// 创建数据
List<Person> people = Arrays.asList(
new Person("Alice", 25, "Engineer"),
new Person("Bob", 30, "Manager"),
new Person("Charlie", 25, "Designer"),
new Person("Diana", 28, "Engineer"),
new Person("Eve", 35, "Manager")
);
// 使用Stream API进行复杂数据处理
Map<String, List<Person>> engineers = people.stream()
.filter(p -> "Engineer".equals(p.getRole())) // 过滤工程师
.filter(p -> p.getAge() > 24) // 年龄大于24
.sorted(Comparator.comparingInt(Person::getAge)) // 按年龄排序
.collect(Collectors.groupingBy(Person::getRole)); // 按角色分组
System.out.println("Engineers: " + engineers.get("Engineer"));
// 使用Optional处理可能为空的结果
Optional<Person> oldestEngineer = people.stream()
.filter(p -> "Engineer".equals(p.getRole()))
.max(Comparator.comparingInt(Person::getAge));
String result = oldestEngineer
.map(p -> p.getName() + " is the oldest engineer")
.orElse("No engineers found");
System.out.println(result);
// 使用Lambda表达式和方法引用
people.stream()
.filter(p -> p.getAge() < 30)
.forEach(System.out::println); // 方法引用
// 使用函数式接口进行自定义操作
Predicate<Person> isYoung = p -> p.getAge() < 30;
Function<Person, String> getName = Person::getName;
List<String> youngNames = people.stream()
.filter(isYoung)
.map(getName)
.collect(Collectors.toList());
System.out.println("Young people: " + youngNames);
}
// 性能对比示例
public static void performanceComparison() {
List<Integer> numbers = IntStream.rangeClosed(1, 1000000)
.boxed()
.collect(Collectors.toList());
// 传统循环方式
long startTime = System.currentTimeMillis();
int traditionalSum = 0;
for (Integer num : numbers) {
if (num % 2 == 0) {
traditionalSum += num;
}
}
long traditionalTime = System.currentTimeMillis() - startTime;
// Stream API方式
startTime = System.currentTimeMillis();
int streamSum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
long streamTime = System.currentTimeMillis() - startTime;
// 并行Stream方式
startTime = System.currentTimeMillis();
int parallelSum = numbers.parallelStream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
long parallelTime = System.currentTimeMillis() - startTime;
System.out.println("Traditional time: " + traditionalTime + "ms, sum: " + traditionalSum);
System.out.println("Stream time: " + streamTime + "ms, sum: " + streamSum);
System.out.println("Parallel time: " + parallelTime + "ms, sum: " + parallelSum);
}
public static void main(String[] args) {
System.out.println("=== Java 8 新特性综合演示 ===\n");
// Lambda表达式演示
System.out.println("1. Lambda表达式:");
LambdaBasics.basicSyntax();
LambdaBasics.typeInference();
LambdaAdvanced.functionComposition();
System.out.println("\n2. Stream API:");
StreamBasics.streamCreation();
StreamBasics.intermediateOperations();
StreamBasics.terminalOperations();
StreamAdvanced.parallelStream();
System.out.println("\n3. Optional类:");
OptionalBasics.optionalCreation();
OptionalBasics.optionalMethods();
OptionalAdvanced.optionalDataProcessing();
System.out.println("\n4. 函数式接口:");
FunctionalInterfaces.predicateExamples();
FunctionalInterfaces.functionExamples();
System.out.println("\n5. 方法引用:");
MethodReferences.staticMethodReferences();
MethodReferences.constructorReferences();
System.out.println("\n6. 接口默认方法:");
DefaultMethods.demonstrateDefaultMethods();
DefaultMethodsAdvanced.demonstrateAdvancedDefaultMethods();
System.out.println("\n7. 日期时间API:");
DateTimeAPI.localDateExamples();
DateTimeAdvanced.dateTimeFormatting();
System.out.println("\n8. Base64编码:");
Base64Example.base64Basic();
System.out.println("\n9. 重复注解:");
RepeatableAnnotations.readRepeatableAnnotations();
System.out.println("\n10. 综合应用:");
integratedExample();
performanceComparison();
System.out.println("\n=== Java 8新特性演示完成 ===");
}
}
Java 8的这些新特性极大地提升了Java编程的现代化水平,特别是函数式编程概念的引入,让代码更加简洁、可读和高效。Lambda表达式、Stream API和Optional等特性已经成为现代Java开发的标准工具,掌握这些特性对于提升开发效率和代码质量具有重要意义。
关于作者
🌟 我是suxiaoxiang,一位热爱技术的开发者
💡 专注于Java生态和前沿技术分享
🚀 持续输出高质量技术内容
如果这篇文章对你有帮助,请支持一下:
👍 点赞
⭐ 收藏
👀 关注
您的支持是我持续创作的动力!感谢每一位读者的关注与认可!