以下是结合Java 8+新特性和实际场景的实操内容,涵盖函数式编程、Stream API、模块化、并发工具等最新技术,并提供完整可运行的示例代码。
技术方案:
Java 8引入的Lambda表达式允许以更简洁的语法实现函数式接口,配合Stream API可大幅提升集合操作效率。函数式接口是只包含一个抽象方法的接口,可用@FunctionalInterface
注解标记。
应用实例:实现一个简单的计算器,支持不同运算操作。
@FunctionalInterface
interface CalculatorOperation {
double calculate(double a, double b);
}
public class LambdaCalculator {
public static void main(String[] args) {
// 使用Lambda表达式实现加减乘除
CalculatorOperation add = (a, b) -> a + b;
CalculatorOperation subtract = (a, b) -> a - b;
CalculatorOperation multiply = (a, b) -> a * b;
CalculatorOperation divide = (a, b) -> {
if (b == 0) throw new IllegalArgumentException("除数不能为零");
return a / b;
};
// 执行运算
System.out.println("加法: " + operate(10, 5, add));
System.out.println("减法: " + operate(10, 5, subtract));
System.out.println("乘法: " + operate(10, 5, multiply));
System.out.println("除法: " + operate(10, 5, divide));
}
private static double operate(double a, double b, CalculatorOperation op) {
return op.calculate(a, b);
}
}
技术方案:
Stream API提供了高效的集合处理方式,支持过滤、映射、排序、聚合等操作,可替代传统的迭代器和循环。
应用实例:统计员工信息(薪资计算、筛选高薪员工)。
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private String name;
private int age;
private double salary;
private String department;
public Employee(String name, int age, double salary, String department) {
this.name = name;
this.age = age;
this.salary = salary;
this.department = department;
}
// Getters
public String getName() { return name; }
public int getAge() { return age; }
public double getSalary() { return salary; }
public String getDepartment() { return department; }
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + ", department='" + department + "'}";
}
}
public class StreamExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", 25, 8000.0, "IT"),
new Employee("Bob", 30, 12000.0, "HR"),
new Employee("Charlie", 35, 15000.0, "IT"),
new Employee("David", 28, 9000.0, "Finance"),
new Employee("Eve", 40, 18000.0, "HR")
);
// 1. 计算所有员工的平均年龄
double averageAge = employees.stream()
.mapToInt(Employee::getAge)
.average()
.orElse(0);
System.out.println("平均年龄: " + averageAge);
// 2. 筛选月薪超过10000的员工并按薪资降序排列
List<Employee> highSalaryEmployees = employees.stream()
.filter(e -> e.getSalary() > 10000)
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
.collect(Collectors.toList());
System.out.println("高薪员工: " + highSalaryEmployees);
// 3. 按部门分组
Map<String, List<Employee>> departmentGroups = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
System.out.println("部门分组: " + departmentGroups);
}
}
技术方案:
Java 8引入的Optional<T>
类用于优雅地处理可能为null
的值,避免NullPointerException
。
应用实例:用户信息查询与处理。
import java.util.Optional;
class User {
private String username;
private String email;
public User(String username, String email) {
this.username = username;
this.email = email;
}
public String getUsername() { return username; }
public Optional<String> getEmail() { return Optional.ofNullable(email); }
}
public class OptionalExample {
public static void main(String[] args) {
User userWithEmail = new User("alice", "alice@example.com");
User userWithoutEmail = new User("bob", null);
// 处理可能为空的email
printEmail(userWithEmail);
printEmail(userWithoutEmail);
// 获取email,没有则使用默认值
String email1 = userWithEmail.getEmail().orElse("default@example.com");
String email2 = userWithoutEmail.getEmail().orElse("default@example.com");
System.out.println("Email1: " + email1);
System.out.println("Email2: " + email2);
// 如果存在则执行操作
userWithEmail.getEmail().ifPresent(email -> System.out.println("发送邮件至: " + email));
}
private static void printEmail(User user) {
user.getEmail()
.map(email -> "邮箱: " + email)
.orElse("未设置邮箱");
}
}
技术方案:
Java 9引入的模块化系统(Jigsaw)通过module-info.java
文件定义模块边界和依赖关系,增强了代码的安全性和可维护性。
应用实例:创建一个简单的模块化应用(用户服务与订单服务)。
// module-info.java (用户模块)
module com.example.userservice {
exports com.example.users;
requires com.example.commons;
}
// module-info.java (订单模块)
module com.example.orderservice {
exports com.example.orders;
requires com.example.userservice;
}
// module-info.java (公共模块)
module com.example.commons {
exports com.example.utils;
}
技术方案:
java.time
包提供了线程安全、不可变且设计良好的日期时间API,替代了旧的Date
和Calendar
类。
应用实例:处理员工考勤记录。
import java.time.*;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
// 当前日期时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间: " + now);
// 解析日期字符串
String dateStr = "2023-06-15";
LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println("解析后的日期: " + date);
// 计算两个时间点之间的差值
LocalTime startTime = LocalTime.of(9, 0);
LocalTime endTime = LocalTime.of(18, 30);
Duration workDuration = Duration.between(startTime, endTime);
System.out.println("工作时长: " + workDuration.toHours() + "小时"
+ (workDuration.toMinutes() % 60) + "分钟");
// 时区转换
ZonedDateTime localTime = ZonedDateTime.now();
ZonedDateTime newYorkTime = localTime.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("本地时间: " + localTime);
System.out.println("纽约时间: " + newYorkTime);
}
}
技术方案:
Java 8引入的CompletableFuture
提供了强大的异步编程能力,支持链式调用、组合操作和异常处理。
应用实例:模拟电商系统中的并行查询(商品信息+库存+价格)。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureExample {
private static final ExecutorService executor = Executors.newFixedThreadPool(3);
public static void main(String[] args) throws ExecutionException, InterruptedException {
String productId = "P12345";
// 并行查询商品信息、库存和价格
CompletableFuture<String> productInfoFuture = CompletableFuture.supplyAsync(
() -> queryProductInfo(productId), executor);
CompletableFuture<Integer> stockFuture = CompletableFuture.supplyAsync(
() -> queryStock(productId), executor);
CompletableFuture<Double> priceFuture = CompletableFuture.supplyAsync(
() -> queryPrice(productId), executor);
// 组合所有结果
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
productInfoFuture, stockFuture, priceFuture);
// 当所有任务完成后,汇总结果
CompletableFuture<String> resultFuture = allFutures.thenApply(v -> {
try {
return "商品: " + productInfoFuture.get() +
", 库存: " + stockFuture.get() +
", 价格: " + priceFuture.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
// 处理结果
resultFuture.thenAccept(System.out::println);
// 关闭线程池
executor.shutdown();
}
private static String queryProductInfo(String productId) {
sleep(1000); // 模拟网络延迟
return "iPhone 14 Pro";
}
private static int queryStock(String productId) {
sleep(800); // 模拟网络延迟
return 42;
}
private static double queryPrice(String productId) {
sleep(1200); // 模拟网络延迟
return 9999.0;
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
技术方案:
Java 8允许接口定义默认方法(default
关键字)和静态方法,增强了接口的扩展性。
应用实例:定义可排序接口并提供默认实现。
interface Sortable {
int getSortValue();
// 默认方法:提供默认的比较逻辑
default int compareTo(Sortable other) {
return Integer.compare(this.getSortValue(), other.getSortValue());
}
// 静态方法:创建排序器
static <T extends Sortable> Comparator<T> createComparator() {
return Comparator.comparingInt(Sortable::getSortValue);
}
}
class Product implements Sortable {
private String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int getSortValue() {
return price;
}
@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + "}";
}
}
public class DefaultMethodExample {
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("手机", 5000),
new Product("电脑", 8000),
new Product("耳机", 1000)
);
// 使用默认方法排序
products.sort(Sortable.createComparator());
System.out.println("按价格排序: " + products);
}
}
特性 | 版本 | 描述 |
---|---|---|
Lambda表达式 | Java 8 | 简化函数式接口的实现,使代码更简洁 |
Stream API | Java 8 | 高效处理集合数据,支持链式操作和并行处理 |
Optional类 | Java 8 | 优雅处理空值,减少NullPointerException |
模块化系统 | Java 9 | 通过module-info.java定义模块边界,增强安全性和可维护性 |
新日期时间API | Java 8 | 线程安全、不可变的日期时间处理API |
CompletableFuture | Java 8 | 强大的异步编程工具,支持组合和链式操作 |
接口默认方法 | Java 8 | 允许接口提供方法实现,增强接口扩展性 |
局部变量类型推断 | Java 10 | 使用var关键字自动推断局部变量类型,减少样板代码 |
这些现代Java技术不仅提升了开发效率,还使代码更加简洁、安全和易于维护。在面试中,结合这些新特性回答问题,能够展示你对Java技术发展趋势的了解和实际应用能力。
Java 基础,面试题,技术方案,应用实例,面向对象,集合框架,多线程,异常处理,JVM,IO 流,并发编程,设计模式,String 类,反射机制,注解
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。