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


相关文章
|
5天前
|
人工智能 Cloud Native Java
2025 年 Java 应届生斩获高薪需掌握的技术实操指南与实战要点解析
本指南为2025年Java应届生打造,涵盖JVM调优、响应式编程、云原生、微服务、实时计算与AI部署等前沿技术,结合电商、数据处理等真实场景,提供可落地的技术实操方案,助力掌握高薪开发技能。
42 2
|
18天前
|
人工智能 Java 程序员
搭建AI智能体的Java神器:Google ADK深度解析
想用Java构建复杂的AI智能体?Google开源的ADK工具包来了!代码优先、模块化设计,让你像搭积木一样轻松组合智能体。从单体到多智能体系统,从简单工具到复杂编排,这篇文章带你玩转Java AI开发的全新境界。
86 1
|
5天前
|
缓存 Java API
Java 面试实操指南与最新技术结合的实战攻略
本指南涵盖Java 17+新特性、Spring Boot 3微服务、响应式编程、容器化部署与数据缓存实操,结合代码案例解析高频面试技术点,助你掌握最新Java技术栈,提升实战能力,轻松应对Java中高级岗位面试。
31 0
|
8天前
|
安全 算法 Java
Java 多线程:线程安全与同步控制的深度解析
本文介绍了 Java 多线程开发的关键技术,涵盖线程的创建与启动、线程安全问题及其解决方案,包括 synchronized 关键字、原子类和线程间通信机制。通过示例代码讲解了多线程编程中的常见问题与优化方法,帮助开发者提升程序性能与稳定性。
46 0
|
22天前
|
缓存 Java 关系型数据库
2025 年最新华为 Java 面试题及答案,全方位打造面试宝典
Java面试高频考点与实践指南(150字摘要) 本文系统梳理了Java面试核心考点,包括Java基础(数据类型、面向对象特性、常用类使用)、并发编程(线程机制、锁原理、并发容器)、JVM(内存模型、GC算法、类加载机制)、Spring框架(IoC/AOP、Bean生命周期、事务管理)、数据库(MySQL引擎、事务隔离、索引优化)及分布式(CAP理论、ID生成、Redis缓存)。同时提供华为级实战代码,涵盖Spring Cloud Alibaba微服务、Sentinel限流、Seata分布式事务,以及完整的D
51 0
|
22天前
|
XML JSON Java
Java 反射:从原理到实战的全面解析与应用指南
本文深度解析Java反射机制,从原理到实战应用全覆盖。首先讲解反射的概念与核心原理,包括类加载过程和`Class`对象的作用;接着详细分析反射的核心API用法,如`Class`、`Constructor`、`Method`和`Field`的操作方法;最后通过动态代理和注解驱动配置解析等实战场景,帮助读者掌握反射技术的实际应用。内容翔实,适合希望深入理解Java反射机制的开发者。
78 13
|
22天前
|
算法 架构师 Java
Java 开发岗及 java 架构师百度校招历年经典面试题汇总
以下是百度校招Java岗位面试题精选摘要(150字): Java开发岗重点关注集合类、并发和系统设计。HashMap线程安全可通过Collections.synchronizedMap()或ConcurrentHashMap实现,后者采用分段锁提升并发性能。负载均衡算法包括轮询、加权轮询和最少连接数,一致性哈希可均匀分布请求。Redis持久化有RDB(快照恢复快)和AOF(日志更安全)两种方式。架构师岗涉及JMM内存模型、happens-before原则和无锁数据结构(基于CAS)。
35 5
|
20天前
|
SQL JSON 安全
Java 8 + 中 Lambda 表达式与 Stream API 的应用解析
摘要:本文介绍了Java 8+核心新特性,包括Lambda表达式与Stream API的集合操作(如过滤统计)、函数式接口的自定义实现、Optional类的空值安全处理、接口默认方法与静态方法的扩展能力,以及Java 9模块化系统的组件管理。每个特性均配有典型应用场景和代码示例,如使用Stream统计字符串长度、Optional处理Map取值、模块化项目的依赖声明等,帮助开发者掌握现代Java的高效编程范式。(150字)
38 1
|
23天前
|
安全 Java API
2025 年 Java 校招面试常见问题及详细答案汇总
本资料涵盖Java校招常见面试题,包括Java基础、并发编程、JVM、Spring框架、分布式与微服务等核心知识点,并提供详细解析与实操代码,助力2025校招备战。
62 1