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

简介: 本内容结合Java 8+新特性与实际场景,涵盖函数式编程、Stream API、模块化、并发工具等技术。通过Lambda表达式、Stream集合操作、Optional空值处理、CompletableFuture异步编程等完整示例代码,助你掌握现代Java应用开发。附面试题解析与技术方案,提升实战能力。代码示例涵盖计算器、员工信息统计、用户查询、模块化系统设计等,助你轻松应对技术挑战。

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

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

现代Java技术应用实例

Lambda表达式与函数式接口

技术方案
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与集合操作

技术方案
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);
    }
}

Optional类处理空值

技术方案
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+)

技术方案
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;
}

新的日期时间API(Java 8)

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

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

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提供了强大的异步编程能力,支持链式调用、组合操作和异常处理。

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

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 基础,面试题,技术方案,应用实例,面向对象,集合框架,多线程,异常处理,Java 并发,IO 流,Java8 新特性,Spring 框架,MyBatis, 数据库连接,设计模式



代码获取方式
https://pan.quark.cn/s/14fcf913bae6


相关文章
|
2月前
|
人工智能 Cloud Native Java
2025 年 Java 应届生斩获高薪需掌握的技术实操指南与实战要点解析
本指南为2025年Java应届生打造,涵盖JVM调优、响应式编程、云原生、微服务、实时计算与AI部署等前沿技术,结合电商、数据处理等真实场景,提供可落地的技术实操方案,助力掌握高薪开发技能。
144 2
|
1月前
|
缓存 安全 Java
Java并发性能优化|读写锁与互斥锁解析
本文深入解析Java中两种核心锁机制——互斥锁与读写锁,通过概念对比、代码示例及性能测试,揭示其适用场景。互斥锁适用于写多或强一致性场景,读写锁则在读多写少时显著提升并发性能。结合锁降级、公平模式等高级特性,助你编写高效稳定的并发程序。
108 0
|
2月前
|
人工智能 Java 程序员
搭建AI智能体的Java神器:Google ADK深度解析
想用Java构建复杂的AI智能体?Google开源的ADK工具包来了!代码优先、模块化设计,让你像搭积木一样轻松组合智能体。从单体到多智能体系统,从简单工具到复杂编排,这篇文章带你玩转Java AI开发的全新境界。
|
2月前
|
缓存 Java API
Java 面试实操指南与最新技术结合的实战攻略
本指南涵盖Java 17+新特性、Spring Boot 3微服务、响应式编程、容器化部署与数据缓存实操,结合代码案例解析高频面试技术点,助你掌握最新Java技术栈,提升实战能力,轻松应对Java中高级岗位面试。
320 0
|
2月前
|
安全 算法 Java
Java 多线程:线程安全与同步控制的深度解析
本文介绍了 Java 多线程开发的关键技术,涵盖线程的创建与启动、线程安全问题及其解决方案,包括 synchronized 关键字、原子类和线程间通信机制。通过示例代码讲解了多线程编程中的常见问题与优化方法,帮助开发者提升程序性能与稳定性。
125 0
|
1月前
|
JavaScript Java 微服务
现代化 Java Web 在线商城项目技术方案与实战开发流程及核心功能实现详解
本项目基于Spring Boot 3与Vue 3构建现代化在线商城系统,采用微服务架构,整合Spring Cloud、Redis、MySQL等技术,涵盖用户认证、商品管理、购物车功能,并支持Docker容器化部署与Kubernetes编排。提供完整CI/CD流程,助力高效开发与扩展。
282 63
|
1月前
|
安全 Oracle Java
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
159 0
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
|
28天前
|
算法 Java 测试技术
零基础学 Java: 从语法入门到企业级项目实战的详细学习路线解析
本文为零基础学习者提供完整的Java学习路线,涵盖语法基础、面向对象编程、数据结构与算法、多线程、JVM原理、Spring框架、Spring Boot及项目实战,助你从入门到进阶,系统掌握Java编程技能,提升实战开发能力。
78 0
|
2月前
|
存储 Java Linux
操作系统层面视角下 Java IO 的演进路径及核心技术变革解析
本文从操作系统层面深入解析Java IO的演进历程,涵盖BIO、NIO、多路复用器及Netty等核心技术。分析各阶段IO模型的原理、优缺点及系统调用机制,探讨Java如何通过底层优化提升并发性能与数据处理效率,全面呈现IO技术的变革路径与发展趋势。
53 1