首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java 基础知识面试题技术方案与应用实例全面解析

Java 基础知识面试题技术方案与应用实例全面解析

原创
作者头像
啦啦啦191
发布2025-06-18 14:54:13
发布2025-06-18 14:54:13
640
举报

以下是结合Java 8+新特性和实际场景的实操内容,涵盖函数式编程、Stream API、模块化、并发工具等最新技术,并提供完整可运行的示例代码。

Java基础知识面试题全解析:技术方案与应用实例(续)

现代Java技术应用实例

Lambda表达式与函数式接口

技术方案

Java 8引入的Lambda表达式允许以更简洁的语法实现函数式接口,配合Stream API可大幅提升集合操作效率。函数式接口是只包含一个抽象方法的接口,可用@FunctionalInterface注解标记。

应用实例:实现一个简单的计算器,支持不同运算操作。

代码语言:java
复制
@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与集合操作

技术方案

Stream API提供了高效的集合处理方式,支持过滤、映射、排序、聚合等操作,可替代传统的迭代器和循环。

应用实例:统计员工信息(薪资计算、筛选高薪员工)。

代码语言:java
复制
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);
    }
}

Optional类处理空值

技术方案

Java 8引入的Optional<T>类用于优雅地处理可能为null的值,避免NullPointerException

应用实例:用户信息查询与处理。

代码语言:java
复制
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+)

技术方案

Java 9引入的模块化系统(Jigsaw)通过module-info.java文件定义模块边界和依赖关系,增强了代码的安全性和可维护性。

应用实例:创建一个简单的模块化应用(用户服务与订单服务)。

代码语言: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;
}

新的日期时间API(Java 8)

技术方案

java.time包提供了线程安全、不可变且设计良好的日期时间API,替代了旧的DateCalendar类。

应用实例:处理员工考勤记录。

代码语言:java
复制
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);
    }
}

CompletableFuture异步编程

技术方案

Java 8引入的CompletableFuture提供了强大的异步编程能力,支持链式调用、组合操作和异常处理。

应用实例:模拟电商系统中的并行查询(商品信息+库存+价格)。

代码语言:java
复制
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关键字)和静态方法,增强了接口的扩展性。

应用实例:定义可排序接口并提供默认实现。

代码语言:java
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Java基础知识面试题全解析:技术方案与应用实例(续)
    • 现代Java技术应用实例
      • Lambda表达式与函数式接口
      • Stream API与集合操作
      • Optional类处理空值
      • 模块化系统(Java 9+)
      • 新的日期时间API(Java 8)
      • CompletableFuture异步编程
      • 接口默认方法与静态方法
      • 新特性总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档