校招Java面试基础题目解析与学习指南(含新技术实操)
八、Java 8+ 新特性
8.1 Lambda表达式与函数式接口
Lambda表达式是Java 8引入的重要特性,用于简化函数式接口的实现。函数式接口是指只包含一个抽象方法的接口。
示例: 使用Lambda表达式实现Runnable接口
java
// 传统方式
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("传统方式实现Runnable");
}
};
// Lambda表达式方式
Runnable runnable2 = () -> System.out.println("Lambda方式实现Runnable");
// 使用示例
new Thread(runnable1).start();
new Thread(runnable2).start();
8.2 Stream API
Stream API用于对集合进行高效处理,支持过滤、映射、排序等操作。
示例: 对列表进行过滤和映射
java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// 过滤偶数并乘以2
List<Integer> result = numbers.stream()
.filter(n -> n % 2 == 0) // 过滤偶数
.map(n -> n * 2) // 每个元素乘以2
.collect(Collectors.toList()); // 收集结果
System.out.println(result); // 输出: [4, 8, 12]
}
}
8.3 Optional类
Optional类用于解决空指针异常(NullPointerException),使代码更健壮。
示例: 使用Optional处理可能为空的值
java
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String nullableString = null;
// 创建Optional对象
Optional<String> optional = Optional.ofNullable(nullableString);
// 使用orElse方法提供默认值
String result = optional.orElse("Default Value");
// 使用ifPresent方法处理值存在的情况
optional.ifPresent(s -> System.out.println("值存在: " + s));
System.out.println(result); // 输出: Default Value
}
}
九、多线程与并发
9.1 CompletableFuture异步编程
Java 8引入的CompletableFuture提供了强大的异步编程能力。
示例: 异步任务组合
java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建异步任务
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from Future 1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from Future 2";
});
// 组合两个异步任务
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> {
return s1 + " and " + s2;
});
// 获取结果
System.out.println(combinedFuture.get());
// 输出: Result from Future 1 and Result from Future 2
}
}
9.2 ReentrantLock与Condition
Java 5引入的ReentrantLock提供了比synchronized更灵活的锁机制。
示例: 使用ReentrantLock和Condition实现生产者-消费者模式
java
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerExample {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity = 5;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
public void produce() throws InterruptedException {
lock.lock();
try {
while (queue.size() == capacity) {
notFull.await(); // 队列满时等待
}
int item = (int) (Math.random() * 100);
queue.add(item);
System.out.println("Produced: " + item);
notEmpty.signal(); // 通知消费者队列非空
} finally {
lock.unlock();
}
}
public void consume() throws InterruptedException {
lock.lock();
try {
while (queue.isEmpty()) {
notEmpty.await(); // 队列空时等待
}
int item = queue.poll();
System.out.println("Consumed: " + item);
notFull.signal(); // 通知生产者队列非满
} finally {
lock.unlock();
}
}
}
十、新的语法特性
10.1 局部变量类型推断(var)
Java 10引入的var关键字允许编译器自动推断局部变量的类型。
示例: 使用var简化变量声明
java
// 传统方式
List<String> names = new ArrayList<>();
Map<Integer, String> map = new HashMap<>();
// 使用var关键字
var namesList = new ArrayList<String>();
var numberMap = new HashMap<Integer, String>();
10.2 文本块(Text Blocks)
Java 13引入的文本块简化了多行字符串的表示。
示例: 使用文本块代替传统字符串拼接
java
// 传统方式
String html = "<html>\n" +
" <body>\n" +
" <h1>Hello, World!</h1>\n" +
" </body>\n" +
"</html>";
// 使用文本块
String htmlBlock = """
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
""";
十一、模块化系统(Java 9+)
Java 9引入的模块化系统(JPMS)增强了代码的安全性和可维护性。
示例: 创建一个简单的模块化应用
java
// module-info.java
module com.example.myapp {
requires java.base;
requires java.sql;
exports com.example.myapp.api;
opens com.example.myapp.impl to java.reflect;
}
// 在模块中使用
package com.example.myapp.api;
public interface Service {
void doSomething();
}
十二、集合与泛型新特性
12.1 不可变集合
Java 9+提供了创建不可变集合的静态工厂方法。
示例: 创建不可变集合
java
// 创建不可变List
List<String> immutableList = List.of("A", "B", "C");
// 创建不可变Set
Set<Integer> immutableSet = Set.of(1, 2, 3);
// 创建不可变Map
Map<String, Integer> immutableMap = Map.of("One", 1, "Two", 2);
12.2 泛型改进
Java 10+对泛型进行了改进,支持更灵活的类型推断。
示例: 使用菱形语法与var结合
java
// Java 7+ 菱形语法
List<String> list = new ArrayList<>();
// Java 10+ 结合var
var map = new HashMap<String, List<Integer>>();
十三、实操项目:在线书店系统
13.1 项目需求
使用Java 8+特性开发一个简单的在线书店系统,包含书籍管理、用户管理和订单管理功能。
13.2 核心代码实现
java
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
// 书籍类
class Book {
private final String id;
private final String title;
private final String author;
private final double price;
public Book(String id, String title, String author, double price) {
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
// Getters
public String getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
@Override
public String toString() {
return "Book{id=%s, title='%s', author='%s', price=%.2f}".formatted(id, title, author, price);
}
}
// 用户类
class User {
private final String id;
private final String name;
private final String email;
private List<Order> orders = new ArrayList<>();
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getters and Setters
public String getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
public List<Order> getOrders() { return orders; }
public void addOrder(Order order) { orders.add(order); }
}
// 订单类
class Order {
private final String id;
private final User user;
private final List<Book> books;
private final LocalDateTime orderTime;
private OrderStatus status;
public Order(String id, User user, List<Book> books) {
this.id = id;
this.user = user;
this.books = books;
this.orderTime = LocalDateTime.now();
this.status = OrderStatus.CREATED;
}
// Getters and Setters
public String getId() { return id; }
public User getUser() { return user; }
public List<Book> getBooks() { return books; }
public LocalDateTime getOrderTime() { return orderTime; }
public OrderStatus getStatus() { return status; }
public void setStatus(OrderStatus status) { this.status = status; }
public double getTotalPrice() {
return books.stream().mapToDouble(Book::getPrice).sum();
}
}
// 订单状态枚举
enum OrderStatus {
CREATED, PAID, SHIPPED, DELIVERED, CANCELLED
}
// 书店服务类
class BookstoreService {
private final List<Book> books = new ArrayList<>();
private final Map<String, User> users = new HashMap<>();
private final Map<String, Order> orders = new HashMap<>();
// 添加书籍
public void addBook(Book book) {
books.add(book);
}
// 根据作者查找书籍
public List<Book> findBooksByAuthor(String author) {
return books.stream()
.filter(book -> book.getAuthor().equalsIgnoreCase(author))
.collect(Collectors.toList());
}
// 创建用户
public User createUser(String id, String name, String email) {
User user = new User(id, name, email);
users.put(id, user);
return user;
}
// 创建订单
public CompletableFuture<Order> createOrderAsync(String userId, List<String> bookIds) {
return CompletableFuture.supplyAsync(() -> {
User user = users.get(userId);
if (user == null) {
throw new IllegalArgumentException("用户不存在: " + userId);
}
List<Book> orderBooks = bookIds.stream()
.map(id -> books.stream()
.filter(b -> b.getId().equals(id))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("书籍不存在: " + id)))
.collect(Collectors.toList());
String orderId = UUID.randomUUID().toString();
Order order = new Order(orderId, user, orderBooks);
orders.put(orderId, order);
user.addOrder(order);
return order;
});
}
// 获取用户订单统计
public Map<String, Double> getUserOrderStatistics() {
return users.values().stream()
.collect(Collectors.toMap(
User::getName,
user -> user.getOrders().stream()
.mapToDouble(Order::getTotalPrice)
.sum(),
(existing, replacement) -> existing // 处理键冲突
));
}
}
// 主类 - 演示使用
public class OnlineBookstore {
public static void main(String[] args) throws Exception {
BookstoreService service = new BookstoreService();
// 添加书籍
service.addBook(new Book("B001", "Java核心技术", "Cay Horstmann", 99.99));
service.addBook(new Book("B002", "Effective Java", "Joshua Bloch", 89.99));
service.addBook(new Book("B003", "Python Crash Course", "Eric Matthes", 79.99));
// 创建用户
User user = service.createUser("U001", "张三", "[email protected]");
// 创建订单(异步)
CompletableFuture<Order> orderFuture = service.createOrderAsync(
"U001", Arrays.asList("B001", "B002"));
orderFuture.thenAccept(order -> {
System.out.println("订单创建成功: " + order.getId());
System.out.println("订单总价: " + order.getTotalPrice());
}).exceptionally(ex -> {
System.out.println("订单创建失败: " + ex.getMessage());
return null;
}).get(); // 等待异步操作完成
// 统计用户消费
Map<String, Double> statistics = service.getUserOrderStatistics();
System.out.println("\n用户消费统计:");
statistics.forEach((name, total) -> System.out.printf("%s: %.2f元%n", name, total));
}
}
这个在线书店系统示例展示了如何结合Java 8+的新特性(Lambda表达式、Stream API、CompletableFuture等)来构建一个现代的Java应用。通过学习和实践这些技术,你将能够更好地应对校招面试中的高级问题。
通过上述代码和解释,你可以看到Java最新技术的实际应用。建议你运行这些示例代码,并尝试根据需求进行扩展,以加深对这些技术的理解。如果你需要进一步的帮助或有任何疑问,请随时告诉我。
代码获取方式
关注我获取更多内容