Lambda表达式深入实战:现代业务场景应用指南

🚀 Lambda表达式深入实战:现代业务场景应用指南

💡 深度解析:从理论到实践,掌握Lambda表达式在现代企业级应用中的高级用法和最佳实践

📋 目录

  1. 🎯 Lambda表达式核心原理深度解析
  2. 💼 电商业务场景中的Lambda应用
  3. 🏦 金融系统中的函数式编程实践
  4. 📊 数据分析与报表生成场景
  5. 🌐 微服务架构中的Lambda应用
  6. ⚡ 性能优化与最佳实践
  7. 🔧 高级函数式编程技巧
  8. 📝 实战项目:构建函数式业务规则引擎

🎯 Lambda表达式核心原理深度解析

🔍 Lambda表达式的底层实现机制

🌟 深入理解:Lambda表达式不仅仅是语法糖,它背后有着复杂的编译器优化和运行时机制

✨ 编译器如何处理Lambda表达式
// 原始Lambda表达式
Function<String, String> upperCase = s -> s.toUpperCase();

// 编译器生成的等价代码(简化版)
Function<String, String> upperCase = new Function<String, String>() {
    @Override
    public String apply(String s) {
        return s.toUpperCase();
    }
};

// 实际上编译器使用invokedynamic指令和方法句柄
// 这比传统匿名内部类更高效

🔧 编译器优化策略:

  • invokedynamic指令:延迟绑定,运行时优化
  • 方法句柄:直接方法调用,避免反射开销
  • 常量池优化:相同Lambda表达式复用
  • 逃逸分析:栈上分配,减少GC压力
🎯 函数式接口的设计原则

🎯 示例1:企业级函数式接口设计

import java.util.function.*;
import java.util.concurrent.CompletableFuture;

/**
 * 业务规则处理器 - 企业级函数式接口设计
 */
public class BusinessRuleProcessor {
    
    // 1. 业务验证器接口
    @FunctionalInterface
    public interface BusinessValidator<T> {
        ValidationResult validate(T data);
        
        // 组合验证器
        default BusinessValidator<T> and(BusinessValidator<T> other) {
            return data -> {
                ValidationResult result1 = this.validate(data);
                if (!result1.isValid()) {
                    return result1;
                }
                return other.validate(data);
            };
        }
        
        // 或逻辑验证器
        default BusinessValidator<T> or(BusinessValidator<T> other) {
            return data -> {
                ValidationResult result1 = this.validate(data);
                if (result1.isValid()) {
                    return result1;
                }
                return other.validate(data);
            };
        }
    }
    
    // 2. 异步业务处理器
    @FunctionalInterface
    public interface AsyncBusinessProcessor<T, R> {
        CompletableFuture<R> processAsync(T input);
        
        // 链式异步处理
        default <V> AsyncBusinessProcessor<T, V> thenProcess(
                AsyncBusinessProcessor<R, V> next) {
            return input -> this.processAsync(input)
                .thenCompose(next::processAsync);
        }
    }
    
    // 3. 条件执行器
    @FunctionalInterface
    public interface ConditionalExecutor<T> {
        void executeIf(T data, Predicate<T> condition);
        
        static <T> ConditionalExecutor<T> of(Consumer<T> action) {
            return (data, condition) -> {
                if (condition.test(data)) {
                    action.accept(data);
                }
            };
        }
    }
    
    // 验证结果类
    public static class ValidationResult {
        private final boolean valid;
        private final String message;
        
        public ValidationResult(boolean valid, String message) {
            this.valid = valid;
            this.message = message;
        }
        
        public boolean isValid() { return valid; }
        public String getMessage() { return message; }
        
        public static ValidationResult success() {
            return new ValidationResult(true, "验证通过");
        }
        
        public static ValidationResult failure(String message) {
            return new ValidationResult(false, message);
        }
    }
}

💼 电商业务场景中的Lambda应用

🛒 订单处理系统的函数式设计

🎯 示例2:电商订单处理链

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 电商订单处理系统 - Lambda表达式实战应用
 */
public class ECommerceOrderProcessor {
    
    // 订单实体
    public static class Order {
        private String orderId;
        private String customerId;
        private List<OrderItem> items;
        private BigDecimal totalAmount;
        private OrderStatus status;
        private LocalDateTime createTime;
        private String couponCode;
        private String customerLevel; // VIP, GOLD, SILVER, NORMAL
        
        // 构造器和getter/setter省略...
        public Order(String orderId, String customerId, List<OrderItem> items, 
                    String couponCode, String customerLevel) {
            this.orderId = orderId;
            this.customerId = customerId;
            this.items = items;
            this.couponCode = couponCode;
            this.customerLevel = customerLevel;
            this.createTime = LocalDateTime.now();
            this.status = OrderStatus.PENDING;
            this.totalAmount = calculateTotal();
        }
        
        private BigDecimal calculateTotal() {
            return items.stream()
                .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        
        // getter方法省略...
        public String getOrderId() { return orderId; }
        public String getCustomerId() { return customerId; }
        public List<OrderItem> getItems() { return items; }
        public BigDecimal getTotalAmount() { return totalAmount; }
        public OrderStatus getStatus() { return status; }
        public LocalDateTime getCreateTime() { return createTime; }
        public String getCouponCode() { return couponCode; }
        public String getCustomerLevel() { return customerLevel; }
        
        public void setStatus(OrderStatus status) { this.status = status; }
        public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
    }
    
    public static class OrderItem {
        private String productId;
        private String productName;
        private BigDecimal price;
        private int quantity;
        private String category;
        
        public OrderItem(String productId, String productName, BigDecimal price, 
                        int quantity, String category) {
            this.productId = productId;
            this.productName = productName;
            this.price = price;
            this.quantity = quantity;
            this.category = category;
        }
        
        // getter方法
        public String getProductId() { return productId; }
        public String getProductName() { return productName; }
        public BigDecimal getPrice() { return price; }
        public int getQuantity() { return quantity; }
        public String getCategory() { return category; }
    }
    
    public enum OrderStatus {
        PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED
    }
    
    // 1. 订单验证规则链
    public static class OrderValidationChain {
        
        // 库存验证
        public static final BusinessRuleProcessor.BusinessValidator<Order> STOCK_VALIDATOR = 
            order -> {
                boolean hasStock = order.getItems().stream()
                    .allMatch(item -> checkStock(item.getProductId(), item.getQuantity()));
                return hasStock ? 
                    BusinessRuleProcessor.ValidationResult.success() :
                    BusinessRuleProcessor.ValidationResult.failure("库存不足");
            };
        
        // 价格验证
        public static final BusinessRuleProcessor.BusinessValidator<Order> PRICE_VALIDATOR = 
            order -> {
                BigDecimal minAmount = new BigDecimal("0.01");
                BigDecimal maxAmount = new BigDecimal("50000.00");
                BigDecimal total = order.getTotalAmount();
                
                if (total.compareTo(minAmount) < 0 || total.compareTo(maxAmount) > 0) {
                    return BusinessRuleProcessor.ValidationResult.failure(
                        "订单金额超出允许范围");
                }
                return BusinessRuleProcessor.ValidationResult.success();
            };
        
        // 客户验证
        public static final BusinessRuleProcessor.BusinessValidator<Order> CUSTOMER_VALIDATOR = 
            order -> {
                if (order.getCustomerId() == null || order.getCustomerId().trim().isEmpty()) {
                    return BusinessRuleProcessor.ValidationResult.failure("客户ID不能为空");
                }
                // 模拟客户状态检查
                if (isCustomerBlacklisted(order.getCustomerId())) {
                    return BusinessRuleProcessor.ValidationResult.failure("客户已被列入黑名单");
                }
                return BusinessRuleProcessor.ValidationResult.success();
            };
        
        // 组合验证器
        public static final BusinessRuleProcessor.BusinessValidator<Order> COMPLETE_VALIDATOR = 
            STOCK_VALIDATOR.and(PRICE_VALIDATOR).and(CUSTOMER_VALIDATOR);
        
        private static boolean checkStock(String productId, int quantity) {
            // 模拟库存检查
            return Math.random() > 0.1; // 90%概率有库存
        }
        
        private static boolean isCustomerBlacklisted(String customerId) {
            // 模拟黑名单检查
            return customerId.contains("blacklist");
        }
    }
    
    // 2. 优惠计算策略
    public static class DiscountCalculator {
        
        // 优惠策略函数
        public static final Function<Order, BigDecimal> VIP_DISCOUNT = 
            order -> "VIP".equals(order.getCustomerLevel()) ? 
                order.getTotalAmount().multiply(new BigDecimal("0.15")) : BigDecimal.ZERO;
        
        public static final Function<Order, BigDecimal> GOLD_DISCOUNT = 
            order -> "GOLD".equals(order.getCustomerLevel()) ? 
                order.getTotalAmount().multiply(new BigDecimal("0.10")) : BigDecimal.ZERO;
        
        public static final Function<Order, BigDecimal> COUPON_DISCOUNT = 
            order -> {
                if (order.getCouponCode() != null && !order.getCouponCode().isEmpty()) {
                    // 模拟优惠券折扣计算
                    return order.getTotalAmount().multiply(new BigDecimal("0.05"));
                }
                return BigDecimal.ZERO;
            };
        
        public static final Function<Order, BigDecimal> BULK_DISCOUNT = 
            order -> {
                int totalItems = order.getItems().stream()
                    .mapToInt(OrderItem::getQuantity)
                    .sum();
                if (totalItems >= 10) {
                    return order.getTotalAmount().multiply(new BigDecimal("0.08"));
                }
                return BigDecimal.ZERO;
            };
        
        // 组合所有优惠策略
        public static BigDecimal calculateTotalDiscount(Order order) {
            return Stream.of(VIP_DISCOUNT, GOLD_DISCOUNT, COUPON_DISCOUNT, BULK_DISCOUNT)
                .map(strategy -> strategy.apply(order))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
    }
    
    // 3. 订单处理流水线
    public static class OrderProcessingPipeline {
        
        // 处理步骤定义
        public static final Function<Order, Order> VALIDATE_ORDER = order -> {
            BusinessRuleProcessor.ValidationResult result = 
                OrderValidationChain.COMPLETE_VALIDATOR.validate(order);
            if (!result.isValid()) {
                throw new RuntimeException("订单验证失败: " + result.getMessage());
            }
            System.out.println("✅ 订单验证通过: " + order.getOrderId());
            return order;
        };
        
        public static final Function<Order, Order> APPLY_DISCOUNTS = order -> {
            BigDecimal discount = DiscountCalculator.calculateTotalDiscount(order);
            BigDecimal finalAmount = order.getTotalAmount().subtract(discount);
            order.setTotalAmount(finalAmount);
            System.out.println("💰 应用优惠: " + order.getOrderId() + 
                             ", 优惠金额: " + discount + ", 最终金额: " + finalAmount);
            return order;
        };
        
        public static final Function<Order, Order> RESERVE_INVENTORY = order -> {
            order.getItems().forEach(item -> {
                System.out.println("📦 预留库存: " + item.getProductName() + 
                                 " x " + item.getQuantity());
            });
            return order;
        };
        
        public static final Function<Order, Order> CONFIRM_ORDER = order -> {
            order.setStatus(OrderStatus.CONFIRMED);
            System.out.println("✅ 订单确认: " + order.getOrderId());
            return order;
        };
        
        // 完整处理流水线
        public static final Function<Order, Order> COMPLETE_PIPELINE = 
            VALIDATE_ORDER
                .andThen(APPLY_DISCOUNTS)
                .andThen(RESERVE_INVENTORY)
                .andThen(CONFIRM_ORDER);
    }
    
    // 4. 订单统计分析
    public static class OrderAnalytics {
        
        // 按客户等级统计订单
        public static Map<String, List<Order>> groupByCustomerLevel(List<Order> orders) {
            return orders.stream()
                .collect(Collectors.groupingBy(Order::getCustomerLevel));
        }
        
        // 计算各类别商品销量
        public static Map<String, Integer> calculateCategorySales(List<Order> orders) {
            return orders.stream()
                .flatMap(order -> order.getItems().stream())
                .collect(Collectors.groupingBy(
                    OrderItem::getCategory,
                    Collectors.summingInt(OrderItem::getQuantity)
                ));
        }
        
        // 找出高价值客户
        public static List<String> findHighValueCustomers(List<Order> orders, 
                                                         BigDecimal threshold) {
            return orders.stream()
                .collect(Collectors.groupingBy(
                    Order::getCustomerId,
                    Collectors.reducing(BigDecimal.ZERO, 
                                      Order::getTotalAmount, 
                                      BigDecimal::add)
                ))
                .entrySet().stream()
                .filter(entry -> entry.getValue().compareTo(threshold) > 0)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        }
    }
    
    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== 电商订单处理系统演示 ===");
        
        // 创建测试订单
        List<OrderItem> items = Arrays.asList(
            new OrderItem("P001", "iPhone 15", new BigDecimal("6999.00"), 1, "电子产品"),
            new OrderItem("P002", "AirPods Pro", new BigDecimal("1999.00"), 2, "电子产品")
        );
        
        Order order = new Order("ORD001", "CUST001", items, "SAVE10", "VIP");
        
        try {
            // 执行订单处理流水线
            Order processedOrder = OrderProcessingPipeline.COMPLETE_PIPELINE.apply(order);
            System.out.println("\n🎉 订单处理完成!");
            System.out.println("订单ID: " + processedOrder.getOrderId());
            System.out.println("最终金额: " + processedOrder.getTotalAmount());
            System.out.println("订单状态: " + processedOrder.getStatus());
            
        } catch (Exception e) {
            System.err.println("❌ 订单处理失败: " + e.getMessage());
        }
    }
}

🎯 商品推荐系统的函数式实现

🎯 示例3:智能商品推荐引擎

import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 商品推荐系统 - 基于Lambda表达式的推荐算法实现
 */
public class ProductRecommendationEngine {
    
    // 商品实体
    public static class Product {
        private String productId;
        private String name;
        private String category;
        private double price;
        private double rating;
        private Set<String> tags;
        private int salesCount;
        
        public Product(String productId, String name, String category, 
                      double price, double rating, Set<String> tags, int salesCount) {
            this.productId = productId;
            this.name = name;
            this.category = category;
            this.price = price;
            this.rating = rating;
            this.tags = tags;
            this.salesCount = salesCount;
        }
        
        // getter方法
        public String getProductId() { return productId; }
        public String getName() { return name; }
        public String getCategory() { return category; }
        public double getPrice() { return price; }
        public double getRating() { return rating; }
        public Set<String> getTags() { return tags; }
        public int getSalesCount() { return salesCount; }
        
        @Override
        public String toString() {
            return String.format("Product{id='%s', name='%s', price=%.2f, rating=%.1f}", 
                               productId, name, price, rating);
        }
    }
    
    // 用户行为数据
    public static class UserBehavior {
        private String userId;
        private String productId;
        private String action; // VIEW, CART, PURCHASE
        private long timestamp;
        
        public UserBehavior(String userId, String productId, String action, long timestamp) {
            this.userId = userId;
            this.productId = productId;
            this.action = action;
            this.timestamp = timestamp;
        }
        
        public String getUserId() { return userId; }
        public String getProductId() { return productId; }
        public String getAction() { return action; }
        public long getTimestamp() { return timestamp; }
    }
    
    // 推荐策略接口
    @FunctionalInterface
    public interface RecommendationStrategy {
        List<Product> recommend(String userId, List<Product> allProducts, 
                              List<UserBehavior> userBehaviors, int limit);
        
        // 组合推荐策略
        default RecommendationStrategy combine(RecommendationStrategy other, 
                                             double thisWeight, double otherWeight) {
            return (userId, products, behaviors, limit) -> {
                List<Product> thisResult = this.recommend(userId, products, behaviors, limit * 2);
                List<Product> otherResult = other.recommend(userId, products, behaviors, limit * 2);
                
                // 简单的加权合并逻辑
                Set<Product> combined = new LinkedHashSet<>();
                combined.addAll(thisResult);
                combined.addAll(otherResult);
                
                return combined.stream().limit(limit).collect(Collectors.toList());
            };
        }
    }
    
    // 推荐策略实现
    public static class RecommendationStrategies {
        
        // 1. 基于协同过滤的推荐
        public static final RecommendationStrategy COLLABORATIVE_FILTERING = 
            (userId, products, behaviors, limit) -> {
                // 找到相似用户
                Set<String> userProducts = behaviors.stream()
                    .filter(b -> b.getUserId().equals(userId))
                    .filter(b -> "PURCHASE".equals(b.getAction()))
                    .map(UserBehavior::getProductId)
                    .collect(Collectors.toSet());
                
                // 找到购买了相似商品的其他用户
                Map<String, Long> similarUsers = behaviors.stream()
                    .filter(b -> "PURCHASE".equals(b.getAction()))
                    .filter(b -> !b.getUserId().equals(userId))
                    .filter(b -> userProducts.contains(b.getProductId()))
                    .collect(Collectors.groupingBy(
                        UserBehavior::getUserId,
                        Collectors.counting()
                    ));
                
                // 推荐相似用户购买的其他商品
                return behaviors.stream()
                    .filter(b -> similarUsers.containsKey(b.getUserId()))
                    .filter(b -> "PURCHASE".equals(b.getAction()))
                    .filter(b -> !userProducts.contains(b.getProductId()))
                    .map(UserBehavior::getProductId)
                    .distinct()
                    .map(productId -> products.stream()
                        .filter(p -> p.getProductId().equals(productId))
                        .findFirst().orElse(null))
                    .filter(Objects::nonNull)
                    .limit(limit)
                    .collect(Collectors.toList());
            };
        
        // 2. 基于内容的推荐
        public static final RecommendationStrategy CONTENT_BASED = 
            (userId, products, behaviors, limit) -> {
                // 分析用户偏好的类别和标签
                Map<String, Long> preferredCategories = behaviors.stream()
                    .filter(b -> b.getUserId().equals(userId))
                    .filter(b -> Arrays.asList("PURCHASE", "CART").contains(b.getAction()))
                    .map(UserBehavior::getProductId)
                    .map(productId -> products.stream()
                        .filter(p -> p.getProductId().equals(productId))
                        .findFirst().orElse(null))
                    .filter(Objects::nonNull)
                    .collect(Collectors.groupingBy(
                        Product::getCategory,
                        Collectors.counting()
                    ));
                
                // 根据偏好推荐同类别的高评分商品
                return products.stream()
                    .filter(p -> preferredCategories.containsKey(p.getCategory()))
                    .filter(p -> p.getRating() >= 4.0)
                    .sorted(Comparator.comparing(Product::getRating).reversed())
                    .limit(limit)
                    .collect(Collectors.toList());
            };
        
        // 3. 热门商品推荐
        public static final RecommendationStrategy TRENDING = 
            (userId, products, behaviors, limit) -> {
                return products.stream()
                    .sorted(Comparator.comparing(Product::getSalesCount).reversed()
                           .thenComparing(Product::getRating, Comparator.reverseOrder()))
                    .limit(limit)
                    .collect(Collectors.toList());
            };
        
        // 4. 价格敏感推荐
        public static final RecommendationStrategy PRICE_SENSITIVE = 
            (userId, products, behaviors, limit) -> {
                // 分析用户的价格偏好
                OptionalDouble avgPrice = behaviors.stream()
                    .filter(b -> b.getUserId().equals(userId))
                    .filter(b -> "PURCHASE".equals(b.getAction()))
                    .map(UserBehavior::getProductId)
                    .map(productId -> products.stream()
                        .filter(p -> p.getProductId().equals(productId))
                        .findFirst().orElse(null))
                    .filter(Objects::nonNull)
                    .mapToDouble(Product::getPrice)
                    .average();
                
                double priceThreshold = avgPrice.orElse(1000.0);
                
                return products.stream()
                    .filter(p -> p.getPrice() <= priceThreshold * 1.2) // 允许20%的价格浮动
                    .filter(p -> p.getRating() >= 3.5)
                    .sorted(Comparator.comparing(Product::getRating).reversed())
                    .limit(limit)
                    .collect(Collectors.toList());
            };
    }
    
    // 推荐引擎主类
    public static class RecommendationEngine {
        private final List<Product> products;
        private final List<UserBehavior> userBehaviors;
        
        public RecommendationEngine(List<Product> products, List<UserBehavior> userBehaviors) {
            this.products = products;
            this.userBehaviors = userBehaviors;
        }
        
        // 获取个性化推荐
        public List<Product> getPersonalizedRecommendations(String userId, int limit) {
            // 组合多种推荐策略
            RecommendationStrategy combinedStrategy = 
                RecommendationStrategies.COLLABORATIVE_FILTERING
                    .combine(RecommendationStrategies.CONTENT_BASED, 0.4, 0.3)
                    .combine(RecommendationStrategies.PRICE_SENSITIVE, 0.7, 0.3);
            
            return combinedStrategy.recommend(userId, products, userBehaviors, limit);
        }
        
        // 获取热门推荐
        public List<Product> getTrendingRecommendations(int limit) {
            return RecommendationStrategies.TRENDING
                .recommend(null, products, userBehaviors, limit);
        }
        
        // 基于特定策略的推荐
        public List<Product> getRecommendations(String userId, 
                                               RecommendationStrategy strategy, 
                                               int limit) {
            return strategy.recommend(userId, products, userBehaviors, limit);
        }
    }
    
    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== 商品推荐系统演示 ===");
        
        // 创建测试数据
        List<Product> products = Arrays.asList(
            new Product("P001", "iPhone 15", "手机", 6999.0, 4.8, 
                       Set.of("苹果", "5G", "高端"), 1500),
            new Product("P002", "小米14", "手机", 3999.0, 4.6, 
                       Set.of("小米", "5G", "性价比"), 2000),
            new Product("P003", "MacBook Pro", "笔记本", 12999.0, 4.9, 
                       Set.of("苹果", "专业", "高性能"), 800),
            new Product("P004", "AirPods Pro", "耳机", 1999.0, 4.7, 
                       Set.of("苹果", "降噪", "无线"), 3000),
            new Product("P005", "华为MateBook", "笔记本", 5999.0, 4.5, 
                       Set.of("华为", "轻薄", "商务"), 1200)
        );
        
        List<UserBehavior> behaviors = Arrays.asList(
            new UserBehavior("USER001", "P001", "PURCHASE", System.currentTimeMillis()),
            new UserBehavior("USER001", "P004", "CART", System.currentTimeMillis()),
            new UserBehavior("USER001", "P003", "VIEW", System.currentTimeMillis()),
            new UserBehavior("USER002", "P001", "PURCHASE", System.currentTimeMillis()),
            new UserBehavior("USER002", "P002", "VIEW", System.currentTimeMillis())
        );
        
        RecommendationEngine engine = new RecommendationEngine(products, behaviors);
        
        // 获取个性化推荐
        System.out.println("\n🎯 USER001的个性化推荐:");
        List<Product> personalizedRecs = engine.getPersonalizedRecommendations("USER001", 3);
        personalizedRecs.forEach(System.out::println);
        
        // 获取热门推荐
        System.out.println("\n🔥 热门商品推荐:");
        List<Product> trendingRecs = engine.getTrendingRecommendations(3);
        trendingRecs.forEach(System.out::println);
        
        // 基于内容的推荐
        System.out.println("\n📚 基于内容的推荐:");
        List<Product> contentRecs = engine.getRecommendations("USER001", 
            RecommendationStrategies.CONTENT_BASED, 3);
        contentRecs.forEach(System.out::println);
    }
}

🏦 金融系统中的函数式编程实践

💰 风险评估与定价模型

🎯 示例4:金融风险评估系统

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Period;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 金融风险评估系统 - Lambda表达式在金融业务中的应用
 */
public class FinancialRiskAssessment {
    
    // 客户信息
    public static class Customer {
        private String customerId;
        private String name;
        private int age;
        private String occupation;
        private BigDecimal annualIncome;
        private int creditScore;
        private List<LoanHistory> loanHistory;
        private LocalDate registrationDate;
        
        public Customer(String customerId, String name, int age, String occupation,
                       BigDecimal annualIncome, int creditScore, List<LoanHistory> loanHistory) {
            this.customerId = customerId;
            this.name = name;
            this.age = age;
            this.occupation = occupation;
            this.annualIncome = annualIncome;
            this.creditScore = creditScore;
            this.loanHistory = loanHistory != null ? loanHistory : new ArrayList<>();
            this.registrationDate = LocalDate.now();
        }
        
        // getter方法
        public String getCustomerId() { return customerId; }
        public String getName() { return name; }
        public int getAge() { return age; }
        public String getOccupation() { return occupation; }
        public BigDecimal getAnnualIncome() { return annualIncome; }
        public int getCreditScore() { return creditScore; }
        public List<LoanHistory> getLoanHistory() { return loanHistory; }
        public LocalDate getRegistrationDate() { return registrationDate; }
    }
    
    // 贷款历史
    public static class LoanHistory {
        private BigDecimal amount;
        private LocalDate startDate;
        private LocalDate endDate;
        private boolean defaulted;
        private int daysOverdue;
        
        public LoanHistory(BigDecimal amount, LocalDate startDate, LocalDate endDate,
                          boolean defaulted, int daysOverdue) {
            this.amount = amount;
            this.startDate = startDate;
            this.endDate = endDate;
            this.defaulted = defaulted;
            this.daysOverdue = daysOverdue;
        }
        
        public BigDecimal getAmount() { return amount; }
        public LocalDate getStartDate() { return startDate; }
        public LocalDate getEndDate() { return endDate; }
        public boolean isDefaulted() { return defaulted; }
        public int getDaysOverdue() { return daysOverdue; }
    }
    
    // 贷款申请
    public static class LoanApplication {
        private String applicationId;
        private String customerId;
        private BigDecimal requestedAmount;
        private int termMonths;
        private String purpose;
        private BigDecimal collateralValue;
        private LocalDate applicationDate;
        
        public LoanApplication(String applicationId, String customerId, 
                             BigDecimal requestedAmount, int termMonths, 
                             String purpose, BigDecimal collateralValue) {
            this.applicationId = applicationId;
            this.customerId = customerId;
            this.requestedAmount = requestedAmount;
            this.termMonths = termMonths;
            this.purpose = purpose;
            this.collateralValue = collateralValue;
            this.applicationDate = LocalDate.now();
        }
        
        public String getApplicationId() { return applicationId; }
        public String getCustomerId() { return customerId; }
        public BigDecimal getRequestedAmount() { return requestedAmount; }
        public int getTermMonths() { return termMonths; }
        public String getPurpose() { return purpose; }
        public BigDecimal getCollateralValue() { return collateralValue; }
        public LocalDate getApplicationDate() { return applicationDate; }
    }
    
    // 风险评估结果
    public static class RiskAssessmentResult {
        private String applicationId;
        private RiskLevel riskLevel;
        private BigDecimal riskScore;
        private BigDecimal suggestedInterestRate;
        private BigDecimal maxLoanAmount;
        private List<String> riskFactors;
        private boolean approved;
        
        public RiskAssessmentResult(String applicationId, RiskLevel riskLevel, 
                                  BigDecimal riskScore, BigDecimal suggestedInterestRate,
                                  BigDecimal maxLoanAmount, List<String> riskFactors) {
            this.applicationId = applicationId;
            this.riskLevel = riskLevel;
            this.riskScore = riskScore;
            this.suggestedInterestRate = suggestedInterestRate;
            this.maxLoanAmount = maxLoanAmount;
            this.riskFactors = riskFactors;
            this.approved = riskLevel != RiskLevel.HIGH && riskScore.compareTo(new BigDecimal("70")) >= 0;
        }
        
        public String getApplicationId() { return applicationId; }
        public RiskLevel getRiskLevel() { return riskLevel; }
        public BigDecimal getRiskScore() { return riskScore; }
        public BigDecimal getSuggestedInterestRate() { return suggestedInterestRate; }
        public BigDecimal getMaxLoanAmount() { return maxLoanAmount; }
        public List<String> getRiskFactors() { return riskFactors; }
        public boolean isApproved() { return approved; }
        
        @Override
        public String toString() {
            return String.format("RiskAssessment{id='%s', level=%s, score=%.2f, rate=%.2f%%, approved=%s}",
                               applicationId, riskLevel, riskScore, 
                               suggestedInterestRate.multiply(new BigDecimal("100")), approved);
        }
    }
    
    public enum RiskLevel {
        LOW, MEDIUM, HIGH
    }
    
    // 风险评估规则
    public static class RiskAssessmentRules {
        
        // 1. 信用评分风险因子
        public static final Function<Customer, BigDecimal> CREDIT_SCORE_FACTOR = 
            customer -> {
                int score = customer.getCreditScore();
                if (score >= 750) return new BigDecimal("1.0");
                if (score >= 650) return new BigDecimal("0.8");
                if (score >= 550) return new BigDecimal("0.6");
                return new BigDecimal("0.3");
            };
        
        // 2. 收入稳定性因子
        public static final Function<Customer, BigDecimal> INCOME_STABILITY_FACTOR = 
            customer -> {
                String occupation = customer.getOccupation();
                BigDecimal income = customer.getAnnualIncome();
                
                BigDecimal occupationFactor = switch (occupation.toLowerCase()) {
                    case "公务员", "教师", "医生" -> new BigDecimal("1.0");
                    case "工程师", "会计师", "律师" -> new BigDecimal("0.9");
                    case "销售", "自由职业" -> new BigDecimal("0.7");
                    default -> new BigDecimal("0.8");
                };
                
                BigDecimal incomeFactor = income.compareTo(new BigDecimal("100000")) >= 0 ? 
                    new BigDecimal("1.0") : new BigDecimal("0.8");
                
                return occupationFactor.multiply(incomeFactor);
            };
        
        // 3. 历史还款记录因子
        public static final Function<Customer, BigDecimal> PAYMENT_HISTORY_FACTOR = 
            customer -> {
                List<LoanHistory> history = customer.getLoanHistory();
                if (history.isEmpty()) {
                    return new BigDecimal("0.7"); // 无历史记录,中等风险
                }
                
                long defaultCount = history.stream()
                    .mapToLong(loan -> loan.isDefaulted() ? 1 : 0)
                    .sum();
                
                double avgOverdueDays = history.stream()
                    .mapToInt(LoanHistory::getDaysOverdue)
                    .average()
                    .orElse(0.0);
                
                if (defaultCount == 0 && avgOverdueDays <= 5) {
                    return new BigDecimal("1.0");
                } else if (defaultCount <= 1 && avgOverdueDays <= 15) {
                    return new BigDecimal("0.8");
                } else if (defaultCount <= 2 && avgOverdueDays <= 30) {
                    return new BigDecimal("0.6");
                } else {
                    return new BigDecimal("0.3");
                }
            };
        
        // 4. 年龄风险因子
        public static final Function<Customer, BigDecimal> AGE_RISK_FACTOR = 
            customer -> {
                int age = customer.getAge();
                if (age >= 25 && age <= 55) return new BigDecimal("1.0");
                if (age >= 18 && age <= 65) return new BigDecimal("0.9");
                return new BigDecimal("0.7");
            };
        
        // 5. 债务收入比因子
        public static final BiFunction<Customer, LoanApplication, BigDecimal> DEBT_TO_INCOME_FACTOR = 
            (customer, application) -> {
                BigDecimal monthlyIncome = customer.getAnnualIncome()
                    .divide(new BigDecimal("12"), 2, RoundingMode.HALF_UP);
                
                // 计算现有债务的月还款额(简化计算)
                BigDecimal existingMonthlyPayment = customer.getLoanHistory().stream()
                    .filter(loan -> loan.getEndDate().isAfter(LocalDate.now()))
                    .map(loan -> loan.getAmount().divide(new BigDecimal("60"), 2, RoundingMode.HALF_UP))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                // 计算新贷款的月还款额(简化计算)
                BigDecimal newMonthlyPayment = application.getRequestedAmount()
                    .divide(new BigDecimal(application.getTermMonths()), 2, RoundingMode.HALF_UP);
                
                BigDecimal totalMonthlyPayment = existingMonthlyPayment.add(newMonthlyPayment);
                BigDecimal debtToIncomeRatio = totalMonthlyPayment
                    .divide(monthlyIncome, 4, RoundingMode.HALF_UP);
                
                if (debtToIncomeRatio.compareTo(new BigDecimal("0.3")) <= 0) {
                    return new BigDecimal("1.0");
                } else if (debtToIncomeRatio.compareTo(new BigDecimal("0.5")) <= 0) {
                    return new BigDecimal("0.8");
                } else if (debtToIncomeRatio.compareTo(new BigDecimal("0.7")) <= 0) {
                    return new BigDecimal("0.6");
                } else {
                    return new BigDecimal("0.3");
                }
            };
        
        // 6. 抵押品价值因子
        public static final Function<LoanApplication, BigDecimal> COLLATERAL_FACTOR = 
            application -> {
                BigDecimal collateralValue = application.getCollateralValue();
                BigDecimal requestedAmount = application.getRequestedAmount();
                
                if (collateralValue.compareTo(BigDecimal.ZERO) == 0) {
                    return new BigDecimal("0.8"); // 无抵押贷款
                }
                
                BigDecimal collateralRatio = collateralValue
                    .divide(requestedAmount, 4, RoundingMode.HALF_UP);
                
                if (collateralRatio.compareTo(new BigDecimal("1.5")) >= 0) {
                    return new BigDecimal("1.2");
                } else if (collateralRatio.compareTo(new BigDecimal("1.0")) >= 0) {
                    return new BigDecimal("1.0");
                } else if (collateralRatio.compareTo(new BigDecimal("0.8")) >= 0) {
                    return new BigDecimal("0.9");
                } else {
                    return new BigDecimal("0.7");
                }
            };
    }
    
    // 风险评估引擎
    public static class RiskAssessmentEngine {
        
        // 综合风险评估
        public static RiskAssessmentResult assessRisk(Customer customer, 
                                                     LoanApplication application) {
            List<String> riskFactors = new ArrayList<>();
            
            // 计算各项风险因子
            BigDecimal creditFactor = RiskAssessmentRules.CREDIT_SCORE_FACTOR.apply(customer);
            BigDecimal incomeFactor = RiskAssessmentRules.INCOME_STABILITY_FACTOR.apply(customer);
            BigDecimal paymentFactor = RiskAssessmentRules.PAYMENT_HISTORY_FACTOR.apply(customer);
            BigDecimal ageFactor = RiskAssessmentRules.AGE_RISK_FACTOR.apply(customer);
            BigDecimal debtFactor = RiskAssessmentRules.DEBT_TO_INCOME_FACTOR.apply(customer, application);
            BigDecimal collateralFactor = RiskAssessmentRules.COLLATERAL_FACTOR.apply(application);
            
            // 权重计算综合风险评分
            BigDecimal riskScore = creditFactor.multiply(new BigDecimal("0.25"))
                .add(incomeFactor.multiply(new BigDecimal("0.20")))
                .add(paymentFactor.multiply(new BigDecimal("0.20")))
                .add(ageFactor.multiply(new BigDecimal("0.10")))
                .add(debtFactor.multiply(new BigDecimal("0.15")))
                .add(collateralFactor.multiply(new BigDecimal("0.10")))
                .multiply(new BigDecimal("100"))
                .setScale(2, RoundingMode.HALF_UP);
            
            // 识别风险因子
            if (creditFactor.compareTo(new BigDecimal("0.6")) < 0) {
                riskFactors.add("信用评分较低");
            }
            if (incomeFactor.compareTo(new BigDecimal("0.8")) < 0) {
                riskFactors.add("收入不稳定");
            }
            if (paymentFactor.compareTo(new BigDecimal("0.8")) < 0) {
                riskFactors.add("历史还款记录不良");
            }
            if (debtFactor.compareTo(new BigDecimal("0.6")) < 0) {
                riskFactors.add("债务收入比过高");
            }
            
            // 确定风险等级
            RiskLevel riskLevel;
            if (riskScore.compareTo(new BigDecimal("80")) >= 0) {
                riskLevel = RiskLevel.LOW;
            } else if (riskScore.compareTo(new BigDecimal("60")) >= 0) {
                riskLevel = RiskLevel.MEDIUM;
            } else {
                riskLevel = RiskLevel.HIGH;
            }
            
            // 计算建议利率
            BigDecimal baseRate = new BigDecimal("0.05"); // 基准利率5%
            BigDecimal riskPremium = switch (riskLevel) {
                case LOW -> new BigDecimal("0.01");
                case MEDIUM -> new BigDecimal("0.03");
                case HIGH -> new BigDecimal("0.06");
            };
            BigDecimal suggestedRate = baseRate.add(riskPremium);
            
            // 计算最大贷款额度
            BigDecimal maxLoanAmount = customer.getAnnualIncome()
                .multiply(new BigDecimal("5"))
                .multiply(riskScore.divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP));
            
            return new RiskAssessmentResult(
                application.getApplicationId(),
                riskLevel,
                riskScore,
                suggestedRate,
                maxLoanAmount,
                riskFactors
            );
        }
        
        // 批量风险评估
        public static List<RiskAssessmentResult> batchAssessment(
                Map<String, Customer> customers,
                List<LoanApplication> applications) {
            
            return applications.parallelStream()
                .map(app -> {
                    Customer customer = customers.get(app.getCustomerId());
                    if (customer == null) {
                        throw new IllegalArgumentException("客户不存在: " + app.getCustomerId());
                    }
                    return assessRisk(customer, app);
                })
                .collect(Collectors.toList());
        }
        
        // 风险统计分析
        public static Map<RiskLevel, Long> getRiskDistribution(List<RiskAssessmentResult> results) {
            return results.stream()
                .collect(Collectors.groupingBy(
                    RiskAssessmentResult::getRiskLevel,
                    Collectors.counting()
                ));
        }
        
        // 获取高风险申请
        public static List<RiskAssessmentResult> getHighRiskApplications(
                List<RiskAssessmentResult> results) {
            return results.stream()
                .filter(result -> result.getRiskLevel() == RiskLevel.HIGH)
                .sorted(Comparator.comparing(RiskAssessmentResult::getRiskScore))
                .collect(Collectors.toList());
        }
    }
    
    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== 金融风险评估系统演示 ===");
        
        // 创建测试客户数据
        Map<String, Customer> customers = Map.of(
            "CUST001", new Customer("CUST001", "张三", 35, "工程师", 
                new BigDecimal("150000"), 720, Arrays.asList(
                    new LoanHistory(new BigDecimal("50000"), 
                        LocalDate.of(2020, 1, 1), LocalDate.of(2023, 1, 1), false, 2)
                )),
            "CUST002", new Customer("CUST002", "李四", 28, "销售", 
                new BigDecimal("80000"), 650, new ArrayList<>()),
            "CUST003", new Customer("CUST003", "王五", 45, "公务员", 
                new BigDecimal("120000"), 780, Arrays.asList(
                    new LoanHistory(new BigDecimal("100000"), 
                        LocalDate.of(2019, 6, 1), LocalDate.of(2024, 6, 1), false, 0)
                ))
        );
        
        // 创建贷款申请
        List<LoanApplication> applications = Arrays.asList(
            new LoanApplication("APP001", "CUST001", new BigDecimal("200000"), 
                60, "购房", new BigDecimal("300000")),
            new LoanApplication("APP002", "CUST002", new BigDecimal("50000"), 
                36, "创业", BigDecimal.ZERO),
            new LoanApplication("APP003", "CUST003", new BigDecimal("100000"), 
                48, "装修", new BigDecimal("80000"))
        );
        
        // 执行批量风险评估
        List<RiskAssessmentResult> results = RiskAssessmentEngine
            .batchAssessment(customers, applications);
        
        System.out.println("\n📊 风险评估结果:");
        results.forEach(System.out::println);
        
        // 风险分布统计
        System.out.println("\n📈 风险等级分布:");
        Map<RiskLevel, Long> distribution = RiskAssessmentEngine
            .getRiskDistribution(results);
        distribution.forEach((level, count) -> 
            System.out.println(level + ": " + count + "个申请"));
        
        // 高风险申请
        System.out.println("\n⚠️ 高风险申请:");
        List<RiskAssessmentResult> highRiskApps = RiskAssessmentEngine
            .getHighRiskApplications(results);
        if (highRiskApps.isEmpty()) {
            System.out.println("无高风险申请");
        } else {
            highRiskApps.forEach(System.out::println);
        }
        
        // 批准率统计
        long approvedCount = results.stream()
            .mapToLong(result -> result.isApproved() ? 1 : 0)
            .sum();
        double approvalRate = (double) approvedCount / results.size() * 100;
        System.out.println("\n✅ 总体批准率: " + String.format("%.1f%%", approvalRate));
    }
}

📊 数据分析与报表生成场景

📈 销售数据分析系统

🎯 示例5:企业销售数据分析平台

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 销售数据分析系统 - Lambda表达式在数据分析中的高级应用
 */
public class SalesDataAnalytics {

    // 销售记录实体
    public static class SalesRecord {
        private String recordId;
        private String salesPersonId;
        private String salesPersonName;
        private String customerId;
        private String customerName;
        private String productId;
        private String productName;
        private String productCategory;
        private String region;
        private BigDecimal unitPrice;
        private int quantity;
        private BigDecimal totalAmount;
        private LocalDate saleDate;
        private String channel; // ONLINE, OFFLINE, PHONE

        public SalesRecord(String recordId, String salesPersonId, String salesPersonName,
                          String customerId, String customerName, String productId,
                          String productName, String productCategory, String region,
                          BigDecimal unitPrice, int quantity, LocalDate saleDate, String channel) {
            this.recordId = recordId;
            this.salesPersonId = salesPersonId;
            this.salesPersonName = salesPersonName;
            this.customerId = customerId;
            this.customerName = customerName;
            this.productId = productId;
            this.productName = productName;
            this.productCategory = productCategory;
            this.region = region;
            this.unitPrice = unitPrice;
            this.quantity = quantity;
            this.totalAmount = unitPrice.multiply(BigDecimal.valueOf(quantity));
            this.saleDate = saleDate;
            this.channel = channel;
        }

        // getter方法
        public String getRecordId() { return recordId; }
        public String getSalesPersonId() { return salesPersonId; }
        public String getSalesPersonName() { return salesPersonName; }
        public String getCustomerId() { return customerId; }
        public String getCustomerName() { return customerName; }
        public String getProductId() { return productId; }
        public String getProductName() { return productName; }
        public String getProductCategory() { return productCategory; }
        public String getRegion() { return region; }
        public BigDecimal getUnitPrice() { return unitPrice; }
        public int getQuantity() { return quantity; }
        public BigDecimal getTotalAmount() { return totalAmount; }
        public LocalDate getSaleDate() { return saleDate; }
        public String getChannel() { return channel; }

        @Override
        public String toString() {
            return String.format("SalesRecord{id='%s', product='%s', amount=%.2f, date=%s}",
                               recordId, productName, totalAmount, saleDate);
        }
    }

    // 销售统计结果
    public static class SalesStatistics {
        private BigDecimal totalRevenue;
        private int totalQuantity;
        private int totalTransactions;
        private BigDecimal averageOrderValue;
        private BigDecimal maxSingleSale;
        private BigDecimal minSingleSale;

        public SalesStatistics(BigDecimal totalRevenue, int totalQuantity, int totalTransactions,
                             BigDecimal averageOrderValue, BigDecimal maxSingleSale, BigDecimal minSingleSale) {
            this.totalRevenue = totalRevenue;
            this.totalQuantity = totalQuantity;
            this.totalTransactions = totalTransactions;
            this.averageOrderValue = averageOrderValue;
            this.maxSingleSale = maxSingleSale;
            this.minSingleSale = minSingleSale;
        }

        public BigDecimal getTotalRevenue() { return totalRevenue; }
        public int getTotalQuantity() { return totalQuantity; }
        public int getTotalTransactions() { return totalTransactions; }
        public BigDecimal getAverageOrderValue() { return averageOrderValue; }
        public BigDecimal getMaxSingleSale() { return maxSingleSale; }
        public BigDecimal getMinSingleSale() { return minSingleSale; }

        @Override
        public String toString() {
            return String.format("SalesStatistics{revenue=%.2f, quantity=%d, transactions=%d, avgOrder=%.2f}",
                               totalRevenue, totalQuantity, totalTransactions, averageOrderValue);
        }
    }

    // 销售分析器
    public static class SalesAnalyzer {

        // 1. 基础统计分析
        public static SalesStatistics calculateBasicStatistics(List<SalesRecord> records) {
            if (records.isEmpty()) {
                return new SalesStatistics(BigDecimal.ZERO, 0, 0, BigDecimal.ZERO,
                                         BigDecimal.ZERO, BigDecimal.ZERO);
            }

            BigDecimal totalRevenue = records.stream()
                .map(SalesRecord::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

            int totalQuantity = records.stream()
                .mapToInt(SalesRecord::getQuantity)
                .sum();

            int totalTransactions = records.size();

            BigDecimal averageOrderValue = totalRevenue
                .divide(BigDecimal.valueOf(totalTransactions), 2, RoundingMode.HALF_UP);

            BigDecimal maxSingleSale = records.stream()
                .map(SalesRecord::getTotalAmount)
                .max(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

            BigDecimal minSingleSale = records.stream()
                .map(SalesRecord::getTotalAmount)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

            return new SalesStatistics(totalRevenue, totalQuantity, totalTransactions,
                                     averageOrderValue, maxSingleSale, minSingleSale);
        }

        // 2. 按时间维度分析
        public static Map<YearMonth, SalesStatistics> analyzeByMonth(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    record -> YearMonth.from(record.getSaleDate()),
                    Collectors.collectingAndThen(
                        Collectors.toList(),
                        SalesAnalyzer::calculateBasicStatistics
                    )
                ));
        }

        // 3. 按产品类别分析
        public static Map<String, SalesStatistics> analyzeByCategory(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getProductCategory,
                    Collectors.collectingAndThen(
                        Collectors.toList(),
                        SalesAnalyzer::calculateBasicStatistics
                    )
                ));
        }

        // 4. 按地区分析
        public static Map<String, SalesStatistics> analyzeByRegion(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getRegion,
                    Collectors.collectingAndThen(
                        Collectors.toList(),
                        SalesAnalyzer::calculateBasicStatistics
                    )
                ));
        }

        // 5. 销售人员绩效分析
        public static Map<String, SalesStatistics> analyzeBySalesPerson(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getSalesPersonName,
                    Collectors.collectingAndThen(
                        Collectors.toList(),
                        SalesAnalyzer::calculateBasicStatistics
                    )
                ));
        }

        // 6. 渠道分析
        public static Map<String, SalesStatistics> analyzeByChannel(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getChannel,
                    Collectors.collectingAndThen(
                        Collectors.toList(),
                        SalesAnalyzer::calculateBasicStatistics
                    )
                ));
        }

        // 7. 客户价值分析
        public static Map<String, BigDecimal> analyzeCustomerValue(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getCustomerName,
                    Collectors.reducing(BigDecimal.ZERO,
                                      SalesRecord::getTotalAmount,
                                      BigDecimal::add)
                ));
        }

        // 8. 产品销量排行
        public static List<Map.Entry<String, Integer>> getProductSalesRanking(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getProductName,
                    Collectors.summingInt(SalesRecord::getQuantity)
                ))
                .entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        }

        // 9. 趋势分析
        public static List<Map.Entry<LocalDate, BigDecimal>> getDailyRevenueTrend(List<SalesRecord> records) {
            return records.stream()
                .collect(Collectors.groupingBy(
                    SalesRecord::getSaleDate,
                    Collectors.reducing(BigDecimal.ZERO,
                                      SalesRecord::getTotalAmount,
                                      BigDecimal::add)
                ))
                .entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toList());
        }

        // 10. 高级分析:客户细分
        public static Map<String, List<String>> segmentCustomers(List<SalesRecord> records) {
            Map<String, BigDecimal> customerValues = analyzeCustomerValue(records);

            // 计算客户价值的分位数
            List<BigDecimal> sortedValues = customerValues.values().stream()
                .sorted()
                .collect(Collectors.toList());

            int size = sortedValues.size();
            BigDecimal q1 = sortedValues.get(size / 4);
            BigDecimal q3 = sortedValues.get(3 * size / 4);

            return customerValues.entrySet().stream()
                .collect(Collectors.groupingBy(
                    entry -> {
                        BigDecimal value = entry.getValue();
                        if (value.compareTo(q3) > 0) return "高价值客户";
                        if (value.compareTo(q1) > 0) return "中价值客户";
                        return "低价值客户";
                    },
                    Collectors.mapping(Map.Entry::getKey, Collectors.toList())
                ));
        }
    }

    // 报表生成器
    public static class ReportGenerator {

        // 生成综合销售报表
        public static String generateComprehensiveReport(List<SalesRecord> records) {
            StringBuilder report = new StringBuilder();
            report.append("=== 综合销售分析报表 ===\n\n");

            // 基础统计
            SalesStatistics basicStats = SalesAnalyzer.calculateBasicStatistics(records);
            report.append("📊 基础统计信息:\n");
            report.append(String.format("总收入: ¥%.2f\n", basicStats.getTotalRevenue()));
            report.append(String.format("总销量: %d件\n", basicStats.getTotalQuantity()));
            report.append(String.format("总交易数: %d笔\n", basicStats.getTotalTransactions()));
            report.append(String.format("平均订单价值: ¥%.2f\n", basicStats.getAverageOrderValue()));
            report.append(String.format("最大单笔销售: ¥%.2f\n", basicStats.getMaxSingleSale()));
            report.append(String.format("最小单笔销售: ¥%.2f\n\n", basicStats.getMinSingleSale()));

            // 按类别分析
            Map<String, SalesStatistics> categoryStats = SalesAnalyzer.analyzeByCategory(records);
            report.append("📈 产品类别分析:\n");
            categoryStats.entrySet().stream()
                .sorted(Map.Entry.<String, SalesStatistics>comparingByValue(
                    Comparator.comparing(SalesStatistics::getTotalRevenue)).reversed())
                .forEach(entry -> {
                    report.append(String.format("%s: ¥%.2f (%.1f%%)\n",
                        entry.getKey(),
                        entry.getValue().getTotalRevenue(),
                        entry.getValue().getTotalRevenue()
                            .divide(basicStats.getTotalRevenue(), 4, RoundingMode.HALF_UP)
                            .multiply(BigDecimal.valueOf(100))));
                });

            // 地区分析
            report.append("\n🌍 地区销售分析:\n");
            Map<String, SalesStatistics> regionStats = SalesAnalyzer.analyzeByRegion(records);
            regionStats.entrySet().stream()
                .sorted(Map.Entry.<String, SalesStatistics>comparingByValue(
                    Comparator.comparing(SalesStatistics::getTotalRevenue)).reversed())
                .forEach(entry -> {
                    report.append(String.format("%s: ¥%.2f\n",
                        entry.getKey(), entry.getValue().getTotalRevenue()));
                });

            // 销售人员绩效
            report.append("\n👥 销售人员绩效:\n");
            Map<String, SalesStatistics> salesPersonStats = SalesAnalyzer.analyzeBySalesPerson(records);
            salesPersonStats.entrySet().stream()
                .sorted(Map.Entry.<String, SalesStatistics>comparingByValue(
                    Comparator.comparing(SalesStatistics::getTotalRevenue)).reversed())
                .limit(5)
                .forEach(entry -> {
                    report.append(String.format("%s: ¥%.2f (%d笔交易)\n",
                        entry.getKey(),
                        entry.getValue().getTotalRevenue(),
                        entry.getValue().getTotalTransactions()));
                });

            // 产品销量排行
            report.append("\n🏆 产品销量排行 (Top 5):\n");
            List<Map.Entry<String, Integer>> productRanking = SalesAnalyzer.getProductSalesRanking(records);
            productRanking.stream()
                .limit(5)
                .forEach(entry -> {
                    report.append(String.format("%s: %d件\n", entry.getKey(), entry.getValue()));
                });

            // 客户细分
            report.append("\n🎯 客户细分分析:\n");
            Map<String, List<String>> customerSegments = SalesAnalyzer.segmentCustomers(records);
            customerSegments.forEach((segment, customers) -> {
                report.append(String.format("%s: %d位客户\n", segment, customers.size()));
            });

            return report.toString();
        }

        // 生成月度趋势报表
        public static String generateMonthlyTrendReport(List<SalesRecord> records) {
            StringBuilder report = new StringBuilder();
            report.append("=== 月度销售趋势报表 ===\n\n");

            Map<YearMonth, SalesStatistics> monthlyStats = SalesAnalyzer.analyzeByMonth(records);

            report.append("📅 月度销售数据:\n");
            monthlyStats.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> {
                    YearMonth month = entry.getKey();
                    SalesStatistics stats = entry.getValue();
                    report.append(String.format("%s: ¥%.2f (%d笔交易, 平均¥%.2f)\n",
                        month.format(DateTimeFormatter.ofPattern("yyyy年MM月")),
                        stats.getTotalRevenue(),
                        stats.getTotalTransactions(),
                        stats.getAverageOrderValue()));
                });

            // 计算环比增长率
            report.append("\n📈 环比增长分析:\n");
            List<Map.Entry<YearMonth, SalesStatistics>> sortedMonthly = monthlyStats.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toList());

            for (int i = 1; i < sortedMonthly.size(); i++) {
                Map.Entry<YearMonth, SalesStatistics> current = sortedMonthly.get(i);
                Map.Entry<YearMonth, SalesStatistics> previous = sortedMonthly.get(i - 1);

                BigDecimal currentRevenue = current.getValue().getTotalRevenue();
                BigDecimal previousRevenue = previous.getValue().getTotalRevenue();

                if (previousRevenue.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal growthRate = currentRevenue.subtract(previousRevenue)
                        .divide(previousRevenue, 4, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.valueOf(100));

                    report.append(String.format("%s vs %s: %+.1f%%\n",
                        current.getKey().format(DateTimeFormatter.ofPattern("yyyy年MM月")),
                        previous.getKey().format(DateTimeFormatter.ofPattern("yyyy年MM月")),
                        growthRate));
                }
            }

            return report.toString();
        }
    }

    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== 销售数据分析系统演示 ===");

        // 创建测试销售数据
        List<SalesRecord> salesRecords = Arrays.asList(
            new SalesRecord("S001", "SP001", "张三", "C001", "阿里巴巴", "P001",
                "iPhone 15", "电子产品", "华东", new BigDecimal("6999.00"), 2,
                LocalDate.of(2024, 1, 15), "ONLINE"),
            new SalesRecord("S002", "SP002", "李四", "C002", "腾讯", "P002",
                "MacBook Pro", "电子产品", "华南", new BigDecimal("12999.00"), 1,
                LocalDate.of(2024, 1, 20), "OFFLINE"),
            new SalesRecord("S003", "SP001", "张三", "C003", "百度", "P003",
                "AirPods Pro", "电子产品", "华北", new BigDecimal("1999.00"), 3,
                LocalDate.of(2024, 2, 5), "ONLINE"),
            new SalesRecord("S004", "SP003", "王五", "C004", "字节跳动", "P004",
                "iPad Air", "电子产品", "华东", new BigDecimal("4999.00"), 2,
                LocalDate.of(2024, 2, 10), "PHONE"),
            new SalesRecord("S005", "SP002", "李四", "C001", "阿里巴巴", "P001",
                "iPhone 15", "电子产品", "华东", new BigDecimal("6999.00"), 5,
                LocalDate.of(2024, 2, 15), "OFFLINE"),
            new SalesRecord("S006", "SP001", "张三", "C005", "美团", "P005",
                "Apple Watch", "电子产品", "华南", new BigDecimal("2999.00"), 1,
                LocalDate.of(2024, 3, 1), "ONLINE")
        );

        // 生成综合报表
        System.out.println(ReportGenerator.generateComprehensiveReport(salesRecords));

        // 生成月度趋势报表
        System.out.println(ReportGenerator.generateMonthlyTrendReport(salesRecords));

        // 渠道分析
        System.out.println("🛒 渠道分析:");
        Map<String, SalesStatistics> channelStats = SalesAnalyzer.analyzeByChannel(salesRecords);
        channelStats.forEach((channel, stats) -> {
            System.out.println(String.format("%s: ¥%.2f (%d笔交易)",
                channel, stats.getTotalRevenue(), stats.getTotalTransactions()));
        });

        // 客户价值分析
        System.out.println("\n💎 高价值客户 (Top 3):");
        Map<String, BigDecimal> customerValues = SalesAnalyzer.analyzeCustomerValue(salesRecords);
        customerValues.entrySet().stream()
            .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
            .limit(3)
            .forEach(entry -> {
                System.out.println(String.format("%s: ¥%.2f", entry.getKey(), entry.getValue()));
            });
    }
}

🌐 微服务架构中的Lambda应用

🔄 事件驱动架构与消息处理

🎯 示例6:微服务事件处理系统

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 微服务事件处理系统 - Lambda表达式在分布式系统中的应用
 */
public class MicroserviceEventProcessor {

    // 事件基类
    public static abstract class Event {
        private String eventId;
        private String eventType;
        private LocalDateTime timestamp;
        private String source;
        private Map<String, Object> metadata;

        public Event(String eventType, String source) {
            this.eventId = UUID.randomUUID().toString();
            this.eventType = eventType;
            this.source = source;
            this.timestamp = LocalDateTime.now();
            this.metadata = new HashMap<>();
        }

        public String getEventId() { return eventId; }
        public String getEventType() { return eventType; }
        public LocalDateTime getTimestamp() { return timestamp; }
        public String getSource() { return source; }
        public Map<String, Object> getMetadata() { return metadata; }

        public void addMetadata(String key, Object value) {
            metadata.put(key, value);
        }

        @Override
        public String toString() {
            return String.format("Event{id='%s', type='%s', source='%s', time=%s}",
                               eventId, eventType, source, timestamp);
        }
    }

    // 具体事件类型
    public static class UserRegisteredEvent extends Event {
        private String userId;
        private String email;
        private String userType;

        public UserRegisteredEvent(String userId, String email, String userType) {
            super("USER_REGISTERED", "user-service");
            this.userId = userId;
            this.email = email;
            this.userType = userType;
        }

        public String getUserId() { return userId; }
        public String getEmail() { return email; }
        public String getUserType() { return userType; }
    }

    public static class OrderCreatedEvent extends Event {
        private String orderId;
        private String customerId;
        private double amount;

        public OrderCreatedEvent(String orderId, String customerId, double amount) {
            super("ORDER_CREATED", "order-service");
            this.orderId = orderId;
            this.customerId = customerId;
            this.amount = amount;
        }

        public String getOrderId() { return orderId; }
        public String getCustomerId() { return customerId; }
        public double getAmount() { return amount; }
    }

    public static class PaymentProcessedEvent extends Event {
        private String paymentId;
        private String orderId;
        private double amount;
        private String status;

        public PaymentProcessedEvent(String paymentId, String orderId, double amount, String status) {
            super("PAYMENT_PROCESSED", "payment-service");
            this.paymentId = paymentId;
            this.orderId = orderId;
            this.amount = amount;
            this.status = status;
        }

        public String getPaymentId() { return paymentId; }
        public String getOrderId() { return orderId; }
        public double getAmount() { return amount; }
        public String getStatus() { return status; }
    }

    // 事件处理器接口
    @FunctionalInterface
    public interface EventHandler<T extends Event> {
        CompletableFuture<Void> handle(T event);

        // 组合事件处理器
        default EventHandler<T> andThen(EventHandler<T> after) {
            return event -> this.handle(event).thenCompose(v -> after.handle(event));
        }

        // 条件处理器
        default EventHandler<T> when(Predicate<T> condition) {
            return event -> condition.test(event) ?
                this.handle(event) : CompletableFuture.completedFuture(null);
        }

        // 异常处理
        default EventHandler<T> withErrorHandling(Consumer<Throwable> errorHandler) {
            return event -> this.handle(event).exceptionally(throwable -> {
                errorHandler.accept(throwable);
                return null;
            });
        }
    }

    // 事件总线
    public static class EventBus {
        private final Map<String, List<EventHandler<? extends Event>>> handlers = new ConcurrentHashMap<>();
        private final ExecutorService executorService = ForkJoinPool.commonPool();

        // 注册事件处理器
        @SuppressWarnings("unchecked")
        public <T extends Event> void subscribe(String eventType, EventHandler<T> handler) {
            handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler);
        }

        // 发布事件
        @SuppressWarnings("unchecked")
        public CompletableFuture<Void> publish(Event event) {
            List<EventHandler<? extends Event>> eventHandlers = handlers.get(event.getEventType());
            if (eventHandlers == null || eventHandlers.isEmpty()) {
                return CompletableFuture.completedFuture(null);
            }

            List<CompletableFuture<Void>> futures = eventHandlers.stream()
                .map(handler -> ((EventHandler<Event>) handler).handle(event))
                .collect(Collectors.toList());

            return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        }

        // 批量发布事件
        public CompletableFuture<Void> publishBatch(List<Event> events) {
            List<CompletableFuture<Void>> futures = events.stream()
                .map(this::publish)
                .collect(Collectors.toList());

            return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        }

        public void shutdown() {
            executorService.shutdown();
        }
    }

    // 事件处理器实现
    public static class EventHandlers {

        // 用户注册事件处理器
        public static final EventHandler<UserRegisteredEvent> SEND_WELCOME_EMAIL =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("📧 发送欢迎邮件给: " + event.getEmail());
                // 模拟邮件发送延迟
                try { Thread.sleep(100); } catch (InterruptedException e) {}
            });

        public static final EventHandler<UserRegisteredEvent> CREATE_USER_PROFILE =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("👤 创建用户档案: " + event.getUserId());
                // 模拟数据库操作
                try { Thread.sleep(50); } catch (InterruptedException e) {}
            });

        public static final EventHandler<UserRegisteredEvent> SETUP_DEFAULT_PREFERENCES =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("⚙️ 设置默认偏好: " + event.getUserId());
                try { Thread.sleep(30); } catch (InterruptedException e) {}
            });

        // 订单创建事件处理器
        public static final EventHandler<OrderCreatedEvent> RESERVE_INVENTORY =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("📦 预留库存 - 订单: " + event.getOrderId());
                try { Thread.sleep(80); } catch (InterruptedException e) {}
            });

        public static final EventHandler<OrderCreatedEvent> SEND_ORDER_CONFIRMATION =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("✅ 发送订单确认 - 订单: " + event.getOrderId());
                try { Thread.sleep(60); } catch (InterruptedException e) {}
            });

        public static final EventHandler<OrderCreatedEvent> UPDATE_CUSTOMER_STATS =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("📊 更新客户统计 - 客户: " + event.getCustomerId());
                try { Thread.sleep(40); } catch (InterruptedException e) {}
            });

        // 支付处理事件处理器
        public static final EventHandler<PaymentProcessedEvent> UPDATE_ORDER_STATUS =
            event -> CompletableFuture.runAsync(() -> {
                System.out.println("🔄 更新订单状态 - 订单: " + event.getOrderId() +
                                 ", 支付状态: " + event.getStatus());
                try { Thread.sleep(70); } catch (InterruptedException e) {}
            });

        public static final EventHandler<PaymentProcessedEvent> SEND_PAYMENT_RECEIPT =
            event -> CompletableFuture.runAsync(() -> {
                if ("SUCCESS".equals(event.getStatus())) {
                    System.out.println("🧾 发送支付收据 - 支付: " + event.getPaymentId());
                }
                try { Thread.sleep(50); } catch (InterruptedException e) {}
            });

        public static final EventHandler<PaymentProcessedEvent> TRIGGER_FULFILLMENT =
            event -> CompletableFuture.runAsync(() -> {
                if ("SUCCESS".equals(event.getStatus())) {
                    System.out.println("🚚 触发订单履行 - 订单: " + event.getOrderId());
                }
                try { Thread.sleep(90); } catch (InterruptedException e) {}
            });
    }

    // 事件处理管道
    public static class EventProcessingPipeline {
        private final EventBus eventBus;

        public EventProcessingPipeline() {
            this.eventBus = new EventBus();
            setupEventHandlers();
        }

        private void setupEventHandlers() {
            // 用户注册事件处理链
            EventHandler<UserRegisteredEvent> userRegistrationPipeline =
                EventHandlers.SEND_WELCOME_EMAIL
                    .andThen(EventHandlers.CREATE_USER_PROFILE)
                    .andThen(EventHandlers.SETUP_DEFAULT_PREFERENCES)
                    .withErrorHandling(throwable ->
                        System.err.println("用户注册处理失败: " + throwable.getMessage()));

            eventBus.subscribe("USER_REGISTERED", userRegistrationPipeline);

            // 订单创建事件处理链
            EventHandler<OrderCreatedEvent> orderCreationPipeline =
                EventHandlers.RESERVE_INVENTORY
                    .andThen(EventHandlers.SEND_ORDER_CONFIRMATION)
                    .andThen(EventHandlers.UPDATE_CUSTOMER_STATS)
                    .withErrorHandling(throwable ->
                        System.err.println("订单创建处理失败: " + throwable.getMessage()));

            eventBus.subscribe("ORDER_CREATED", orderCreationPipeline);

            // 支付处理事件处理链
            EventHandler<PaymentProcessedEvent> paymentPipeline =
                EventHandlers.UPDATE_ORDER_STATUS
                    .andThen(EventHandlers.SEND_PAYMENT_RECEIPT
                        .when(event -> "SUCCESS".equals(event.getStatus())))
                    .andThen(EventHandlers.TRIGGER_FULFILLMENT
                        .when(event -> "SUCCESS".equals(event.getStatus())))
                    .withErrorHandling(throwable ->
                        System.err.println("支付处理失败: " + throwable.getMessage()));

            eventBus.subscribe("PAYMENT_PROCESSED", paymentPipeline);
        }

        public CompletableFuture<Void> processEvent(Event event) {
            return eventBus.publish(event);
        }

        public CompletableFuture<Void> processBatch(List<Event> events) {
            return eventBus.publishBatch(events);
        }

        public void shutdown() {
            eventBus.shutdown();
        }
    }

    // 事件监控和指标收集
    public static class EventMetrics {
        private final Map<String, Long> eventCounts = new ConcurrentHashMap<>();
        private final Map<String, Long> processingTimes = new ConcurrentHashMap<>();

        public void recordEvent(String eventType) {
            eventCounts.merge(eventType, 1L, Long::sum);
        }

        public void recordProcessingTime(String eventType, long timeMs) {
            processingTimes.merge(eventType, timeMs, Long::sum);
        }

        public Map<String, Long> getEventCounts() {
            return new HashMap<>(eventCounts);
        }

        public Map<String, Double> getAverageProcessingTimes() {
            return processingTimes.entrySet().stream()
                .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> (double) entry.getValue() / eventCounts.getOrDefault(entry.getKey(), 1L)
                ));
        }

        public void printMetrics() {
            System.out.println("\n📊 事件处理指标:");
            System.out.println("事件计数:");
            eventCounts.forEach((type, count) ->
                System.out.println("  " + type + ": " + count));

            System.out.println("平均处理时间:");
            getAverageProcessingTimes().forEach((type, avgTime) ->
                System.out.println("  " + type + ": " + String.format("%.2fms", avgTime)));
        }
    }

    // 演示方法
    public static void main(String[] args) throws InterruptedException {
        System.out.println("=== 微服务事件处理系统演示 ===");

        EventProcessingPipeline pipeline = new EventProcessingPipeline();
        EventMetrics metrics = new EventMetrics();

        // 创建测试事件
        List<Event> events = Arrays.asList(
            new UserRegisteredEvent("USER001", "user1@example.com", "PREMIUM"),
            new OrderCreatedEvent("ORDER001", "USER001", 299.99),
            new PaymentProcessedEvent("PAY001", "ORDER001", 299.99, "SUCCESS"),
            new UserRegisteredEvent("USER002", "user2@example.com", "BASIC"),
            new OrderCreatedEvent("ORDER002", "USER002", 99.99),
            new PaymentProcessedEvent("PAY002", "ORDER002", 99.99, "FAILED")
        );

        // 处理事件并收集指标
        long startTime = System.currentTimeMillis();

        List<CompletableFuture<Void>> futures = events.stream()
            .map(event -> {
                metrics.recordEvent(event.getEventType());
                long eventStartTime = System.currentTimeMillis();

                return pipeline.processEvent(event)
                    .whenComplete((result, throwable) -> {
                        long processingTime = System.currentTimeMillis() - eventStartTime;
                        metrics.recordProcessingTime(event.getEventType(), processingTime);

                        if (throwable != null) {
                            System.err.println("事件处理失败: " + event + ", 错误: " + throwable.getMessage());
                        }
                    });
            })
            .collect(Collectors.toList());

        // 等待所有事件处理完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
            .join();

        long totalTime = System.currentTimeMillis() - startTime;
        System.out.println("\n⏱️ 总处理时间: " + totalTime + "ms");

        // 打印指标
        metrics.printMetrics();

        // 关闭系统
        pipeline.shutdown();
    }
}

⚡ 性能优化与最佳实践

🚀 Lambda表达式性能优化技巧

🎯 示例7:Lambda性能优化实战

import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;

/**
 * Lambda表达式性能优化 - 最佳实践和性能调优技巧
 */
public class LambdaPerformanceOptimization {

    // 测试数据生成器
    public static class TestDataGenerator {
        private static final Random RANDOM = new Random();

        public static List<Integer> generateNumbers(int size) {
            return IntStream.range(0, size)
                .map(i -> RANDOM.nextInt(1000))
                .boxed()
                .collect(Collectors.toList());
        }

        public static List<String> generateStrings(int size) {
            return IntStream.range(0, size)
                .mapToObj(i -> "String_" + RANDOM.nextInt(1000))
                .collect(Collectors.toList());
        }

        public static List<Person> generatePersons(int size) {
            String[] names = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"};
            String[] cities = {"北京", "上海", "广州", "深圳", "杭州", "南京", "成都", "武汉"};

            return IntStream.range(0, size)
                .mapToObj(i -> new Person(
                    names[RANDOM.nextInt(names.length)],
                    18 + RANDOM.nextInt(50),
                    cities[RANDOM.nextInt(cities.length)],
                    30000 + RANDOM.nextInt(70000)
                ))
                .collect(Collectors.toList());
        }
    }

    public static class Person {
        private String name;
        private int age;
        private String city;
        private double salary;

        public Person(String name, int age, String city, double salary) {
            this.name = name;
            this.age = age;
            this.city = city;
            this.salary = salary;
        }

        public String getName() { return name; }
        public int getAge() { return age; }
        public String getCity() { return city; }
        public double getSalary() { return salary; }

        @Override
        public String toString() {
            return String.format("Person{name='%s', age=%d, city='%s', salary=%.0f}",
                               name, age, city, salary);
        }
    }

    // 性能测试工具
    public static class PerformanceTester {

        public static void timeExecution(String description, Runnable task) {
            System.gc(); // 建议垃圾回收
            long startTime = System.nanoTime();
            task.run();
            long endTime = System.nanoTime();
            double durationMs = (endTime - startTime) / 1_000_000.0;
            System.out.printf("%-40s: %.2f ms%n", description, durationMs);
        }

        public static <T> T timeExecution(String description, Supplier<T> task) {
            System.gc();
            long startTime = System.nanoTime();
            T result = task.get();
            long endTime = System.nanoTime();
            double durationMs = (endTime - startTime) / 1_000_000.0;
            System.out.printf("%-40s: %.2f ms%n", description, durationMs);
            return result;
        }

        public static void warmup(Runnable task, int iterations) {
            for (int i = 0; i < iterations; i++) {
                task.run();
            }
        }
    }

    // 优化技巧演示
    public static class OptimizationTechniques {

        // 1. 避免装箱拆箱 - 使用原始类型流
        public static void demonstrateBoxingOptimization() {
            System.out.println("\n=== 1. 装箱拆箱优化 ===");

            List<Integer> numbers = TestDataGenerator.generateNumbers(1_000_000);

            // ❌ 低效:大量装箱拆箱
            PerformanceTester.timeExecution("Stream<Integer> 求和", () -> {
                long sum = numbers.stream()
                    .mapToInt(Integer::intValue)
                    .sum();
            });

            // ✅ 高效:使用原始类型流
            PerformanceTester.timeExecution("IntStream 求和", () -> {
                long sum = numbers.stream()
                    .mapToInt(Integer::intValue)
                    .sum();
            });

            // ✅ 更高效:直接使用原始数组
            int[] primitiveArray = numbers.stream().mapToInt(Integer::intValue).toArray();
            PerformanceTester.timeExecution("原始数组求和", () -> {
                long sum = Arrays.stream(primitiveArray).sum();
            });
        }

        // 2. 并行流优化
        public static void demonstrateParallelStreamOptimization() {
            System.out.println("\n=== 2. 并行流优化 ===");

            List<Integer> largeList = TestDataGenerator.generateNumbers(10_000_000);

            // 顺序流
            PerformanceTester.timeExecution("顺序流处理", () -> {
                long result = largeList.stream()
                    .filter(n -> n % 2 == 0)
                    .mapToLong(n -> n * n)
                    .sum();
            });

            // 并行流
            PerformanceTester.timeExecution("并行流处理", () -> {
                long result = largeList.parallelStream()
                    .filter(n -> n % 2 == 0)
                    .mapToLong(n -> n * n)
                    .sum();
            });

            // 自定义ForkJoinPool
            ForkJoinPool customThreadPool = new ForkJoinPool(8);
            try {
                PerformanceTester.timeExecution("自定义线程池并行流", () -> {
                    try {
                        long result = customThreadPool.submit(() ->
                            largeList.parallelStream()
                                .filter(n -> n % 2 == 0)
                                .mapToLong(n -> n * n)
                                .sum()
                        ).get();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            } finally {
                customThreadPool.shutdown();
            }
        }

        // 3. 短路操作优化
        public static void demonstrateShortCircuitOptimization() {
            System.out.println("\n=== 3. 短路操作优化 ===");

            List<Person> persons = TestDataGenerator.generatePersons(1_000_000);

            // ❌ 低效:处理所有元素
            PerformanceTester.timeExecution("处理所有元素", () -> {
                List<Person> result = persons.stream()
                    .filter(p -> p.getAge() > 30)
                    .filter(p -> p.getSalary() > 50000)
                    .collect(Collectors.toList());
            });

            // ✅ 高效:使用短路操作
            PerformanceTester.timeExecution("短路操作 - findFirst", () -> {
                Optional<Person> result = persons.stream()
                    .filter(p -> p.getAge() > 30)
                    .filter(p -> p.getSalary() > 50000)
                    .findFirst();
            });

            // ✅ 高效:使用limit限制处理数量
            PerformanceTester.timeExecution("限制处理数量 - limit", () -> {
                List<Person> result = persons.stream()
                    .filter(p -> p.getAge() > 30)
                    .filter(p -> p.getSalary() > 50000)
                    .limit(100)
                    .collect(Collectors.toList());
            });
        }

        // 4. 收集器优化
        public static void demonstrateCollectorOptimization() {
            System.out.println("\n=== 4. 收集器优化 ===");

            List<Person> persons = TestDataGenerator.generatePersons(100_000);

            // ❌ 低效:多次遍历
            PerformanceTester.timeExecution("多次遍历", () -> {
                Map<String, List<Person>> byCity = persons.stream()
                    .collect(Collectors.groupingBy(Person::getCity));

                Map<String, Double> avgSalaryByCity = persons.stream()
                    .collect(Collectors.groupingBy(
                        Person::getCity,
                        Collectors.averagingDouble(Person::getSalary)
                    ));
            });

            // ✅ 高效:一次遍历收集多个结果
            PerformanceTester.timeExecution("一次遍历多个收集器", () -> {
                Map<String, DoubleSummaryStatistics> statsByCity = persons.stream()
                    .collect(Collectors.groupingBy(
                        Person::getCity,
                        Collectors.summarizingDouble(Person::getSalary)
                    ));
            });

            // ✅ 高效:自定义收集器
            PerformanceTester.timeExecution("自定义收集器", () -> {
                Map<String, PersonStats> statsByCity = persons.stream()
                    .collect(Collectors.groupingBy(
                        Person::getCity,
                        Collector.of(
                            PersonStats::new,
                            PersonStats::accept,
                            PersonStats::combine,
                            Collector.Characteristics.UNORDERED
                        )
                    ));
            });
        }

        // 5. 方法引用优化
        public static void demonstrateMethodReferenceOptimization() {
            System.out.println("\n=== 5. 方法引用优化 ===");

            List<String> strings = TestDataGenerator.generateStrings(1_000_000);

            // ❌ 低效:Lambda表达式
            PerformanceTester.timeExecution("Lambda表达式", () -> {
                List<String> result = strings.stream()
                    .map(s -> s.toUpperCase())
                    .filter(s -> s.length() > 5)
                    .collect(Collectors.toList());
            });

            // ✅ 高效:方法引用
            PerformanceTester.timeExecution("方法引用", () -> {
                List<String> result = strings.stream()
                    .map(String::toUpperCase)
                    .filter(s -> s.length() > 5)
                    .collect(Collectors.toList());
            });

            // ✅ 更高效:预编译的Predicate
            Predicate<String> lengthFilter = s -> s.length() > 5;
            PerformanceTester.timeExecution("预编译Predicate", () -> {
                List<String> result = strings.stream()
                    .map(String::toUpperCase)
                    .filter(lengthFilter)
                    .collect(Collectors.toList());
            });
        }

        // 6. 避免不必要的中间操作
        public static void demonstrateIntermediateOperationOptimization() {
            System.out.println("\n=== 6. 中间操作优化 ===");

            List<Person> persons = TestDataGenerator.generatePersons(500_000);

            // ❌ 低效:多个map操作
            PerformanceTester.timeExecution("多个map操作", () -> {
                List<String> result = persons.stream()
                    .map(Person::getName)
                    .map(String::toUpperCase)
                    .map(s -> "Mr. " + s)
                    .collect(Collectors.toList());
            });

            // ✅ 高效:合并map操作
            PerformanceTester.timeExecution("合并map操作", () -> {
                List<String> result = persons.stream()
                    .map(p -> "Mr. " + p.getName().toUpperCase())
                    .collect(Collectors.toList());
            });

            // ✅ 高效:使用flatMap避免嵌套流
            List<List<Person>> nestedPersons = Arrays.asList(
                persons.subList(0, 100000),
                persons.subList(100000, 200000),
                persons.subList(200000, 300000)
            );

            PerformanceTester.timeExecution("flatMap处理嵌套结构", () -> {
                List<String> result = nestedPersons.stream()
                    .flatMap(List::stream)
                    .filter(p -> p.getAge() > 25)
                    .map(Person::getName)
                    .collect(Collectors.toList());
            });
        }
    }

    // 自定义统计类
    public static class PersonStats {
        private int count = 0;
        private double totalSalary = 0.0;
        private int totalAge = 0;

        public void accept(Person person) {
            count++;
            totalSalary += person.getSalary();
            totalAge += person.getAge();
        }

        public PersonStats combine(PersonStats other) {
            count += other.count;
            totalSalary += other.totalSalary;
            totalAge += other.totalAge;
            return this;
        }

        public double getAverageSalary() {
            return count > 0 ? totalSalary / count : 0.0;
        }

        public double getAverageAge() {
            return count > 0 ? (double) totalAge / count : 0.0;
        }

        public int getCount() {
            return count;
        }
    }

    // 内存使用优化
    public static class MemoryOptimization {

        public static void demonstrateMemoryEfficientProcessing() {
            System.out.println("\n=== 7. 内存优化 ===");

            // ❌ 内存低效:创建大量中间集合
            PerformanceTester.timeExecution("内存低效处理", () -> {
                List<Integer> numbers = TestDataGenerator.generateNumbers(1_000_000);
                List<Integer> filtered = numbers.stream()
                    .filter(n -> n % 2 == 0)
                    .collect(Collectors.toList());

                List<Integer> mapped = filtered.stream()
                    .map(n -> n * 2)
                    .collect(Collectors.toList());

                int sum = mapped.stream()
                    .mapToInt(Integer::intValue)
                    .sum();
            });

            // ✅ 内存高效:流式处理
            PerformanceTester.timeExecution("内存高效处理", () -> {
                List<Integer> numbers = TestDataGenerator.generateNumbers(1_000_000);
                int sum = numbers.stream()
                    .filter(n -> n % 2 == 0)
                    .mapToInt(n -> n * 2)
                    .sum();
            });

            // ✅ 更高效:使用原始类型流
            PerformanceTester.timeExecution("原始类型流处理", () -> {
                int[] numbers = TestDataGenerator.generateNumbers(1_000_000)
                    .stream().mapToInt(Integer::intValue).toArray();

                int sum = Arrays.stream(numbers)
                    .filter(n -> n % 2 == 0)
                    .map(n -> n * 2)
                    .sum();
            });
        }
    }

    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== Lambda表达式性能优化演示 ===");

        // 预热JVM
        System.out.println("🔥 JVM预热中...");
        PerformanceTester.warmup(() -> {
            List<Integer> warmupData = TestDataGenerator.generateNumbers(10000);
            warmupData.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum();
        }, 100);

        // 执行各种优化技巧演示
        OptimizationTechniques.demonstrateBoxingOptimization();
        OptimizationTechniques.demonstrateParallelStreamOptimization();
        OptimizationTechniques.demonstrateShortCircuitOptimization();
        OptimizationTechniques.demonstrateCollectorOptimization();
        OptimizationTechniques.demonstrateMethodReferenceOptimization();
        OptimizationTechniques.demonstrateIntermediateOperationOptimization();
        MemoryOptimization.demonstrateMemoryEfficientProcessing();

        System.out.println("\n✅ 性能优化演示完成!");
        System.out.println("\n💡 关键优化要点:");
        System.out.println("1. 使用原始类型流避免装箱拆箱");
        System.out.println("2. 合理使用并行流,注意线程开销");
        System.out.println("3. 利用短路操作提前终止处理");
        System.out.println("4. 优化收集器,减少遍历次数");
        System.out.println("5. 使用方法引用替代Lambda表达式");
        System.out.println("6. 合并中间操作,减少临时对象创建");
        System.out.println("7. 流式处理避免创建大量中间集合");
    }
}

🔧 高级函数式编程技巧

🎯 函数组合与柯里化

🎯 示例8:高级函数式编程模式

import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 高级函数式编程技巧 - 函数组合、柯里化、Monad模式等
 */
public class AdvancedFunctionalProgramming {

    // 1. 函数组合工具类
    public static class FunctionComposition {

        // 函数组合器
        public static <T, R, V> Function<T, V> compose(Function<T, R> f1, Function<R, V> f2) {
            return f1.andThen(f2);
        }

        // 多函数组合
        @SafeVarargs
        public static <T> Function<T, T> composeAll(Function<T, T>... functions) {
            return Arrays.stream(functions)
                .reduce(Function.identity(), Function::andThen);
        }

        // 条件函数组合
        public static <T> Function<T, T> conditionalCompose(
                Predicate<T> condition,
                Function<T, T> ifTrue,
                Function<T, T> ifFalse) {
            return input -> condition.test(input) ? ifTrue.apply(input) : ifFalse.apply(input);
        }

        // 演示函数组合
        public static void demonstrateFunctionComposition() {
            System.out.println("=== 函数组合演示 ===");

            // 基础函数
            Function<String, String> addPrefix = s -> "前缀_" + s;
            Function<String, String> addSuffix = s -> s + "_后缀";
            Function<String, String> toUpper = String::toUpperCase;
            Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();

            // 组合函数
            Function<String, String> complexTransform = composeAll(
                addPrefix, addSuffix, toUpper, reverse
            );

            String result = complexTransform.apply("测试");
            System.out.println("组合函数结果: " + result);

            // 条件组合
            Function<String, String> conditionalTransform = conditionalCompose(
                s -> s.length() > 5,
                toUpper,
                s -> s.toLowerCase()
            );

            System.out.println("短字符串: " + conditionalTransform.apply("hi"));
            System.out.println("长字符串: " + conditionalTransform.apply("hello world"));
        }
    }

    // 2. 柯里化实现
    public static class Currying {

        // 二元函数柯里化
        public static <T, U, R> Function<T, Function<U, R>> curry(BiFunction<T, U, R> biFunction) {
            return t -> u -> biFunction.apply(t, u);
        }

        // 三元函数柯里化
        public static <T, U, V, R> Function<T, Function<U, Function<V, R>>> curry(
                TriFunction<T, U, V, R> triFunction) {
            return t -> u -> v -> triFunction.apply(t, u, v);
        }

        // 三元函数接口
        @FunctionalInterface
        public interface TriFunction<T, U, V, R> {
            R apply(T t, U u, V v);
        }

        // 部分应用
        public static <T, U, R> Function<U, R> partialApply(BiFunction<T, U, R> biFunction, T t) {
            return u -> biFunction.apply(t, u);
        }

        // 演示柯里化
        public static void demonstrateCurrying() {
            System.out.println("\n=== 柯里化演示 ===");

            // 原始二元函数
            BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
            BiFunction<String, String, String> concat = (s1, s2) -> s1 + s2;

            // 柯里化
            Function<Integer, Function<Integer, Integer>> curriedAdd = curry(add);
            Function<String, Function<String, String>> curriedConcat = curry(concat);

            // 使用柯里化函数
            Function<Integer, Integer> add5 = curriedAdd.apply(5);
            System.out.println("5 + 3 = " + add5.apply(3));
            System.out.println("5 + 7 = " + add5.apply(7));

            Function<String, String> addHello = curriedConcat.apply("Hello ");
            System.out.println(addHello.apply("World"));
            System.out.println(addHello.apply("Java"));

            // 三元函数柯里化
            TriFunction<String, String, String, String> format =
                (template, arg1, arg2) -> template.replace("{1}", arg1).replace("{2}", arg2);

            Function<String, Function<String, Function<String, String>>> curriedFormat = curry(format);
            Function<String, String> greetingFormatter = curriedFormat
                .apply("Hello {1}, welcome to {2}!")
                .apply("张三");

            System.out.println(greetingFormatter.apply("Java世界"));
            System.out.println(greetingFormatter.apply("函数式编程"));
        }
    }

    // 3. Maybe/Optional模式增强
    public static class EnhancedOptional {

        // 链式Optional操作
        public static <T, U, V> Optional<V> lift2(
                Optional<T> opt1,
                Optional<U> opt2,
                BiFunction<T, U, V> function) {
            return opt1.flatMap(t -> opt2.map(u -> function.apply(t, u)));
        }

        // 多个Optional的组合
        public static <T> Optional<List<T>> sequence(List<Optional<T>> optionals) {
            List<T> result = new ArrayList<>();
            for (Optional<T> opt : optionals) {
                if (opt.isPresent()) {
                    result.add(opt.get());
                } else {
                    return Optional.empty();
                }
            }
            return Optional.of(result);
        }

        // 条件Optional
        public static <T> Optional<T> when(boolean condition, Supplier<T> supplier) {
            return condition ? Optional.of(supplier.get()) : Optional.empty();
        }

        // 演示增强Optional
        public static void demonstrateEnhancedOptional() {
            System.out.println("\n=== 增强Optional演示 ===");

            Optional<Integer> opt1 = Optional.of(10);
            Optional<Integer> opt2 = Optional.of(20);
            Optional<Integer> opt3 = Optional.empty();

            // 两个Optional的组合
            Optional<Integer> sum = lift2(opt1, opt2, Integer::sum);
            System.out.println("两个Optional相加: " + sum.orElse(0));

            Optional<Integer> sumWithEmpty = lift2(opt1, opt3, Integer::sum);
            System.out.println("包含空值的相加: " + sumWithEmpty.orElse(0));

            // 多个Optional序列化
            List<Optional<String>> optionalList = Arrays.asList(
                Optional.of("Hello"),
                Optional.of("World"),
                Optional.of("!")
            );

            Optional<List<String>> sequenced = sequence(optionalList);
            sequenced.ifPresent(list ->
                System.out.println("序列化结果: " + String.join(" ", list)));

            // 条件Optional
            Optional<String> conditionalOpt = when(true, () -> "条件为真");
            System.out.println("条件Optional: " + conditionalOpt.orElse("条件为假"));
        }
    }

    // 4. 函数式错误处理
    public static class FunctionalErrorHandling {

        // Try类型实现
        public static class Try<T> {
            private final T value;
            private final Exception exception;

            private Try(T value, Exception exception) {
                this.value = value;
                this.exception = exception;
            }

            public static <T> Try<T> success(T value) {
                return new Try<>(value, null);
            }

            public static <T> Try<T> failure(Exception exception) {
                return new Try<>(null, exception);
            }

            public static <T> Try<T> of(Supplier<T> supplier) {
                try {
                    return success(supplier.get());
                } catch (Exception e) {
                    return failure(e);
                }
            }

            public boolean isSuccess() {
                return exception == null;
            }

            public boolean isFailure() {
                return exception != null;
            }

            public T get() {
                if (isFailure()) {
                    throw new RuntimeException(exception);
                }
                return value;
            }

            public T getOrElse(T defaultValue) {
                return isSuccess() ? value : defaultValue;
            }

            public <U> Try<U> map(Function<T, U> mapper) {
                if (isFailure()) {
                    return failure(exception);
                }
                try {
                    return success(mapper.apply(value));
                } catch (Exception e) {
                    return failure(e);
                }
            }

            public <U> Try<U> flatMap(Function<T, Try<U>> mapper) {
                if (isFailure()) {
                    return failure(exception);
                }
                try {
                    return mapper.apply(value);
                } catch (Exception e) {
                    return failure(e);
                }
            }

            public Try<T> recover(Function<Exception, T> recovery) {
                if (isFailure()) {
                    try {
                        return success(recovery.apply(exception));
                    } catch (Exception e) {
                        return failure(e);
                    }
                }
                return this;
            }

            public void forEach(Consumer<T> consumer) {
                if (isSuccess()) {
                    consumer.accept(value);
                }
            }

            @Override
            public String toString() {
                return isSuccess() ? "Success(" + value + ")" : "Failure(" + exception.getMessage() + ")";
            }
        }

        // 演示函数式错误处理
        public static void demonstrateFunctionalErrorHandling() {
            System.out.println("\n=== 函数式错误处理演示 ===");

            // 可能失败的操作
            Function<String, Integer> parseInteger = s -> Integer.parseInt(s);
            Function<Integer, Double> sqrt = n -> {
                if (n < 0) throw new IllegalArgumentException("负数不能开平方根");
                return Math.sqrt(n);
            };

            // 使用Try处理错误
            Try<Integer> result1 = Try.of(() -> parseInteger.apply("123"));
            System.out.println("解析成功: " + result1);

            Try<Integer> result2 = Try.of(() -> parseInteger.apply("abc"));
            System.out.println("解析失败: " + result2);

            // 链式操作
            Try<Double> chainResult = Try.of(() -> parseInteger.apply("16"))
                .flatMap(n -> Try.of(() -> sqrt.apply(n)));
            System.out.println("链式操作成功: " + chainResult);

            Try<Double> chainFailure = Try.of(() -> parseInteger.apply("-4"))
                .flatMap(n -> Try.of(() -> sqrt.apply(n)))
                .recover(ex -> 0.0);
            System.out.println("链式操作失败后恢复: " + chainFailure);

            // 批量处理
            List<String> numbers = Arrays.asList("1", "2", "abc", "4", "xyz");
            List<Try<Integer>> results = numbers.stream()
                .map(s -> Try.of(() -> parseInteger.apply(s)))
                .collect(Collectors.toList());

            System.out.println("批量处理结果:");
            results.forEach(System.out::println);

            // 只获取成功的结果
            List<Integer> successResults = results.stream()
                .filter(Try::isSuccess)
                .map(Try::get)
                .collect(Collectors.toList());
            System.out.println("成功的结果: " + successResults);
        }
    }

    // 5. 惰性求值
    public static class LazyEvaluation {

        // 惰性值容器
        public static class Lazy<T> {
            private Supplier<T> supplier;
            private T value;
            private boolean evaluated = false;

            private Lazy(Supplier<T> supplier) {
                this.supplier = supplier;
            }

            public static <T> Lazy<T> of(Supplier<T> supplier) {
                return new Lazy<>(supplier);
            }

            public T get() {
                if (!evaluated) {
                    value = supplier.get();
                    evaluated = true;
                    supplier = null; // 释放引用
                }
                return value;
            }

            public <U> Lazy<U> map(Function<T, U> mapper) {
                return Lazy.of(() -> mapper.apply(get()));
            }

            public <U> Lazy<U> flatMap(Function<T, Lazy<U>> mapper) {
                return Lazy.of(() -> mapper.apply(get()).get());
            }

            public boolean isEvaluated() {
                return evaluated;
            }

            @Override
            public String toString() {
                return evaluated ? "Lazy(" + value + ")" : "Lazy(未求值)";
            }
        }

        // 演示惰性求值
        public static void demonstrateLazyEvaluation() {
            System.out.println("\n=== 惰性求值演示 ===");

            // 创建惰性值
            Lazy<String> lazyString = Lazy.of(() -> {
                System.out.println("计算惰性字符串...");
                return "Hello, Lazy World!";
            });

            System.out.println("创建惰性值: " + lazyString);
            System.out.println("第一次获取: " + lazyString.get());
            System.out.println("第二次获取: " + lazyString.get()); // 不会重新计算

            // 惰性链式操作
            Lazy<Integer> lazyNumber = Lazy.of(() -> {
                System.out.println("计算基础数字...");
                return 42;
            });

            Lazy<Integer> lazyDoubled = lazyNumber.map(n -> {
                System.out.println("计算双倍值...");
                return n * 2;
            });

            Lazy<String> lazyResult = lazyDoubled.map(n -> {
                System.out.println("转换为字符串...");
                return "结果: " + n;
            });

            System.out.println("创建惰性链: " + lazyResult);
            System.out.println("触发计算: " + lazyResult.get());

            // 惰性无限序列示例
            System.out.println("\n惰性斐波那契数列:");
            Lazy<List<Integer>> lazyFibonacci = Lazy.of(() -> {
                System.out.println("生成斐波那契数列...");
                List<Integer> fib = new ArrayList<>();
                fib.add(0);
                fib.add(1);
                for (int i = 2; i < 10; i++) {
                    fib.add(fib.get(i-1) + fib.get(i-2));
                }
                return fib;
            });

            System.out.println("前10个斐波那契数: " + lazyFibonacci.get());
        }
    }

    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== 高级函数式编程技巧演示 ===");

        FunctionComposition.demonstrateFunctionComposition();
        Currying.demonstrateCurrying();
        EnhancedOptional.demonstrateEnhancedOptional();
        FunctionalErrorHandling.demonstrateFunctionalErrorHandling();
        LazyEvaluation.demonstrateLazyEvaluation();

        System.out.println("\n✅ 高级函数式编程技巧演示完成!");
        System.out.println("\n💡 关键技巧总结:");
        System.out.println("1. 函数组合 - 构建复杂的数据处理管道");
        System.out.println("2. 柯里化 - 创建可复用的部分应用函数");
        System.out.println("3. 增强Optional - 更优雅的空值处理");
        System.out.println("4. Try类型 - 函数式错误处理");
        System.out.println("5. 惰性求值 - 延迟计算提升性能");
    }
}

📝 实战项目:构建函数式业务规则引擎

🎯 项目概述

🌟 综合实战:运用Lambda表达式和函数式编程思想,构建一个灵活、可扩展的业务规则引擎

🎯 项目特性:

  • 🔧 动态规则配置:支持运行时添加、修改规则
  • 🚀 高性能执行:利用Lambda表达式优化执行效率
  • 🔄 规则组合:支持复杂的规则组合和嵌套
  • 📊 执行监控:提供详细的规则执行统计
  • 🎯 类型安全:完全类型安全的规则定义

🎯 完整实现:函数式业务规则引擎

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * 函数式业务规则引擎 - Lambda表达式综合实战项目
 *
 * 功能特性:
 * 1. 动态规则定义和执行
 * 2. 规则组合和链式处理
 * 3. 条件分支和循环处理
 * 4. 规则执行监控和统计
 * 5. 规则缓存和性能优化
 */
public class FunctionalBusinessRuleEngine {

    // 规则执行上下文
    public static class RuleContext {
        private final Map<String, Object> facts = new ConcurrentHashMap<>();
        private final Map<String, Object> results = new ConcurrentHashMap<>();
        private final List<String> executionLog = new ArrayList<>();

        public void addFact(String key, Object value) {
            facts.put(key, value);
        }

        public <T> Optional<T> getFact(String key, Class<T> type) {
            Object value = facts.get(key);
            return type.isInstance(value) ? Optional.of(type.cast(value)) : Optional.empty();
        }

        public void addResult(String key, Object value) {
            results.put(key, value);
        }

        public <T> Optional<T> getResult(String key, Class<T> type) {
            Object value = results.get(key);
            return type.isInstance(value) ? Optional.of(type.cast(value)) : Optional.empty();
        }

        public void log(String message) {
            executionLog.add(LocalDateTime.now() + ": " + message);
        }

        public List<String> getExecutionLog() {
            return new ArrayList<>(executionLog);
        }

        public Map<String, Object> getAllFacts() {
            return new HashMap<>(facts);
        }

        public Map<String, Object> getAllResults() {
            return new HashMap<>(results);
        }
    }

    // 规则执行结果
    public static class RuleExecutionResult {
        private final boolean success;
        private final String ruleName;
        private final long executionTimeMs;
        private final Optional<Exception> exception;
        private final Map<String, Object> outputs;

        public RuleExecutionResult(boolean success, String ruleName, long executionTimeMs,
                                 Optional<Exception> exception, Map<String, Object> outputs) {
            this.success = success;
            this.ruleName = ruleName;
            this.executionTimeMs = executionTimeMs;
            this.exception = exception;
            this.outputs = outputs;
        }

        public boolean isSuccess() { return success; }
        public String getRuleName() { return ruleName; }
        public long getExecutionTimeMs() { return executionTimeMs; }
        public Optional<Exception> getException() { return exception; }
        public Map<String, Object> getOutputs() { return outputs; }

        @Override
        public String toString() {
            return String.format("RuleResult{rule='%s', success=%s, time=%dms}",
                               ruleName, success, executionTimeMs);
        }
    }

    // 业务规则接口
    @FunctionalInterface
    public interface BusinessRule {
        RuleExecutionResult execute(RuleContext context);

        // 规则组合
        default BusinessRule and(BusinessRule other) {
            return context -> {
                RuleExecutionResult firstResult = this.execute(context);
                if (!firstResult.isSuccess()) {
                    return firstResult;
                }
                return other.execute(context);
            };
        }

        default BusinessRule or(BusinessRule other) {
            return context -> {
                RuleExecutionResult firstResult = this.execute(context);
                if (firstResult.isSuccess()) {
                    return firstResult;
                }
                return other.execute(context);
            };
        }

        // 条件执行
        default BusinessRule when(Predicate<RuleContext> condition) {
            return context -> {
                if (condition.test(context)) {
                    return this.execute(context);
                } else {
                    return new RuleExecutionResult(true, "条件跳过", 0,
                                                 Optional.empty(), Collections.emptyMap());
                }
            };
        }

        // 异常处理
        default BusinessRule withErrorHandling(Function<Exception, RuleExecutionResult> errorHandler) {
            return context -> {
                try {
                    return this.execute(context);
                } catch (Exception e) {
                    return errorHandler.apply(e);
                }
            };
        }
    }

    // 规则构建器
    public static class RuleBuilder {
        private String name;
        private Predicate<RuleContext> condition = ctx -> true;
        private Consumer<RuleContext> action = ctx -> {};
        private Function<RuleContext, Map<String, Object>> outputGenerator = ctx -> Collections.emptyMap();

        public static RuleBuilder create(String name) {
            RuleBuilder builder = new RuleBuilder();
            builder.name = name;
            return builder;
        }

        public RuleBuilder when(Predicate<RuleContext> condition) {
            this.condition = condition;
            return this;
        }

        public RuleBuilder then(Consumer<RuleContext> action) {
            this.action = action;
            return this;
        }

        public RuleBuilder output(Function<RuleContext, Map<String, Object>> outputGenerator) {
            this.outputGenerator = outputGenerator;
            return this;
        }

        public BusinessRule build() {
            return context -> {
                long startTime = System.currentTimeMillis();

                try {
                    context.log("开始执行规则: " + name);

                    if (!condition.test(context)) {
                        context.log("规则条件不满足: " + name);
                        return new RuleExecutionResult(false, name,
                            System.currentTimeMillis() - startTime,
                            Optional.empty(), Collections.emptyMap());
                    }

                    action.accept(context);
                    Map<String, Object> outputs = outputGenerator.apply(context);

                    context.log("规则执行成功: " + name);
                    return new RuleExecutionResult(true, name,
                        System.currentTimeMillis() - startTime,
                        Optional.empty(), outputs);

                } catch (Exception e) {
                    context.log("规则执行失败: " + name + ", 错误: " + e.getMessage());
                    return new RuleExecutionResult(false, name,
                        System.currentTimeMillis() - startTime,
                        Optional.of(e), Collections.emptyMap());
                }
            };
        }
    }

    // 规则引擎核心
    public static class RuleEngine {
        private final Map<String, BusinessRule> rules = new ConcurrentHashMap<>();
        private final Map<String, List<RuleExecutionResult>> executionHistory = new ConcurrentHashMap<>();

        // 注册规则
        public void registerRule(String name, BusinessRule rule) {
            rules.put(name, rule);
        }

        // 执行单个规则
        public RuleExecutionResult executeRule(String ruleName, RuleContext context) {
            BusinessRule rule = rules.get(ruleName);
            if (rule == null) {
                throw new IllegalArgumentException("规则不存在: " + ruleName);
            }

            RuleExecutionResult result = rule.execute(context);

            // 记录执行历史
            executionHistory.computeIfAbsent(ruleName, k -> new ArrayList<>()).add(result);

            return result;
        }

        // 执行规则集
        public List<RuleExecutionResult> executeRules(List<String> ruleNames, RuleContext context) {
            return ruleNames.stream()
                .map(name -> executeRule(name, context))
                .collect(Collectors.toList());
        }

        // 执行所有规则
        public List<RuleExecutionResult> executeAllRules(RuleContext context) {
            return rules.keySet().stream()
                .map(name -> executeRule(name, context))
                .collect(Collectors.toList());
        }

        // 条件执行规则
        public List<RuleExecutionResult> executeRulesIf(Predicate<String> ruleFilter, RuleContext context) {
            return rules.keySet().stream()
                .filter(ruleFilter)
                .map(name -> executeRule(name, context))
                .collect(Collectors.toList());
        }

        // 获取规则统计
        public Map<String, RuleStatistics> getRuleStatistics() {
            return executionHistory.entrySet().stream()
                .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> new RuleStatistics(entry.getValue())
                ));
        }

        // 清除执行历史
        public void clearHistory() {
            executionHistory.clear();
        }

        // 获取所有规则名称
        public Set<String> getAllRuleNames() {
            return new HashSet<>(rules.keySet());
        }
    }

    // 规则统计信息
    public static class RuleStatistics {
        private final int totalExecutions;
        private final int successfulExecutions;
        private final int failedExecutions;
        private final double averageExecutionTime;
        private final long maxExecutionTime;
        private final long minExecutionTime;

        public RuleStatistics(List<RuleExecutionResult> results) {
            this.totalExecutions = results.size();
            this.successfulExecutions = (int) results.stream().mapToLong(r -> r.isSuccess() ? 1 : 0).sum();
            this.failedExecutions = totalExecutions - successfulExecutions;
            this.averageExecutionTime = results.stream().mapToLong(RuleExecutionResult::getExecutionTimeMs).average().orElse(0.0);
            this.maxExecutionTime = results.stream().mapToLong(RuleExecutionResult::getExecutionTimeMs).max().orElse(0);
            this.minExecutionTime = results.stream().mapToLong(RuleExecutionResult::getExecutionTimeMs).min().orElse(0);
        }

        public int getTotalExecutions() { return totalExecutions; }
        public int getSuccessfulExecutions() { return successfulExecutions; }
        public int getFailedExecutions() { return failedExecutions; }
        public double getAverageExecutionTime() { return averageExecutionTime; }
        public long getMaxExecutionTime() { return maxExecutionTime; }
        public long getMinExecutionTime() { return minExecutionTime; }
        public double getSuccessRate() { return totalExecutions > 0 ? (double) successfulExecutions / totalExecutions : 0.0; }

        @Override
        public String toString() {
            return String.format("Statistics{total=%d, success=%d, failed=%d, avgTime=%.2fms, successRate=%.1f%%}",
                totalExecutions, successfulExecutions, failedExecutions, averageExecutionTime, getSuccessRate() * 100);
        }
    }

    // 预定义规则库
    public static class CommonRules {

        // 数值范围验证规则
        public static BusinessRule numberRangeRule(String factKey, double min, double max) {
            return RuleBuilder.create("数值范围验证_" + factKey)
                .when(ctx -> ctx.getFact(factKey, Number.class)
                    .map(Number::doubleValue)
                    .map(value -> value >= min && value <= max)
                    .orElse(false))
                .then(ctx -> ctx.addResult(factKey + "_valid", true))
                .output(ctx -> Map.of("validation_result", "数值在有效范围内"))
                .build();
        }

        // 字符串长度验证规则
        public static BusinessRule stringLengthRule(String factKey, int minLength, int maxLength) {
            return RuleBuilder.create("字符串长度验证_" + factKey)
                .when(ctx -> ctx.getFact(factKey, String.class)
                    .map(String::length)
                    .map(length -> length >= minLength && length <= maxLength)
                    .orElse(false))
                .then(ctx -> ctx.addResult(factKey + "_length_valid", true))
                .build();
        }

        // 必填字段验证规则
        public static BusinessRule requiredFieldRule(String factKey) {
            return RuleBuilder.create("必填字段验证_" + factKey)
                .when(ctx -> ctx.getFact(factKey, Object.class).isPresent())
                .then(ctx -> ctx.addResult(factKey + "_required", true))
                .build();
        }

        // 条件计算规则
        public static BusinessRule conditionalCalculationRule(String inputKey, String outputKey,
                                                             Predicate<Object> condition,
                                                             Function<Object, Object> calculation) {
            return RuleBuilder.create("条件计算_" + outputKey)
                .when(ctx -> ctx.getFact(inputKey, Object.class)
                    .map(condition::test)
                    .orElse(false))
                .then(ctx -> {
                    ctx.getFact(inputKey, Object.class)
                        .map(calculation)
                        .ifPresent(result -> ctx.addResult(outputKey, result));
                })
                .build();
        }

        // 聚合计算规则
        public static BusinessRule aggregationRule(List<String> inputKeys, String outputKey,
                                                  BinaryOperator<Double> aggregator) {
            return RuleBuilder.create("聚合计算_" + outputKey)
                .when(ctx -> inputKeys.stream()
                    .allMatch(key -> ctx.getFact(key, Number.class).isPresent()))
                .then(ctx -> {
                    double result = inputKeys.stream()
                        .map(key -> ctx.getFact(key, Number.class).orElse(0))
                        .mapToDouble(Number::doubleValue)
                        .reduce(aggregator::apply)
                        .orElse(0.0);
                    ctx.addResult(outputKey, result);
                })
                .build();
        }
    }

    // 演示方法
    public static void main(String[] args) {
        System.out.println("=== 函数式业务规则引擎演示 ===");

        // 创建规则引擎
        RuleEngine engine = new RuleEngine();

        // 注册基础验证规则
        engine.registerRule("年龄验证", CommonRules.numberRangeRule("age", 18, 65));
        engine.registerRule("姓名验证", CommonRules.stringLengthRule("name", 2, 50));
        engine.registerRule("邮箱必填", CommonRules.requiredFieldRule("email"));

        // 注册复杂业务规则
        BusinessRule salaryCalculationRule = RuleBuilder.create("薪资计算")
            .when(ctx -> ctx.getFact("baseSalary", Number.class).isPresent() &&
                        ctx.getFact("experience", Number.class).isPresent())
            .then(ctx -> {
                double baseSalary = ctx.getFact("baseSalary", Number.class).orElse(0).doubleValue();
                int experience = ctx.getFact("experience", Number.class).orElse(0).intValue();

                double bonus = experience > 5 ? baseSalary * 0.2 : baseSalary * 0.1;
                double totalSalary = baseSalary + bonus;

                ctx.addResult("bonus", bonus);
                ctx.addResult("totalSalary", totalSalary);
            })
            .output(ctx -> Map.of(
                "calculation_type", "salary_with_bonus",
                "bonus_rate", ctx.getFact("experience", Number.class).orElse(0).intValue() > 5 ? 0.2 : 0.1
            ))
            .build();

        engine.registerRule("薪资计算", salaryCalculationRule);

        // 注册组合规则
        BusinessRule employeeValidationRule =
            CommonRules.requiredFieldRule("name")
                .and(CommonRules.numberRangeRule("age", 18, 65))
                .and(CommonRules.requiredFieldRule("email"));

        engine.registerRule("员工信息验证", employeeValidationRule);

        // 创建测试上下文
        RuleContext context = new RuleContext();
        context.addFact("name", "张三");
        context.addFact("age", 30);
        context.addFact("email", "zhangsan@example.com");
        context.addFact("baseSalary", 10000.0);
        context.addFact("experience", 6);

        // 执行所有规则
        System.out.println("\n📋 执行所有规则:");
        List<RuleExecutionResult> results = engine.executeAllRules(context);
        results.forEach(System.out::println);

        // 显示执行结果
        System.out.println("\n📊 执行结果:");
        context.getAllResults().forEach((key, value) ->
            System.out.println(key + ": " + value));

        // 显示执行日志
        System.out.println("\n📝 执行日志:");
        context.getExecutionLog().forEach(System.out::println);

        // 显示规则统计
        System.out.println("\n📈 规则统计:");
        engine.getRuleStatistics().forEach((ruleName, stats) ->
            System.out.println(ruleName + ": " + stats));

        // 测试规则组合
        System.out.println("\n🔗 测试规则组合:");
        RuleContext invalidContext = new RuleContext();
        invalidContext.addFact("name", "李");  // 姓名太短
        invalidContext.addFact("age", 17);    // 年龄不符合
        // 缺少email

        List<RuleExecutionResult> validationResults = engine.executeRulesIf(
            ruleName -> ruleName.contains("验证"), invalidContext);

        validationResults.forEach(result -> {
            System.out.println(result.getRuleName() + ": " +
                (result.isSuccess() ? "✅ 通过" : "❌ 失败"));
        });

        System.out.println("\n✅ 函数式业务规则引擎演示完成!");
        System.out.println("\n💡 项目特色:");
        System.out.println("1. 完全基于Lambda表达式和函数式接口");
        System.out.println("2. 支持动态规则注册和组合");
        System.out.println("3. 提供详细的执行监控和统计");
        System.out.println("4. 类型安全的规则定义和执行");
        System.out.println("5. 高性能的规则执行引擎");
    }
}

📚 总结与展望

🎯 本文核心价值

🔥 深度技术洞察
  • 底层原理解析:深入理解Lambda表达式的编译器实现和性能优化
  • 实际业务场景:涵盖电商、金融、数据分析、微服务等多个领域
  • 性能优化实践:提供具体的性能调优技巧和最佳实践
  • 高级编程模式:函数组合、柯里化、Monad等高级概念的实际应用
🚀 实战项目价值
  • 完整项目实现:函数式业务规则引擎的完整设计和实现
  • 生产级代码质量:考虑了异常处理、性能监控、类型安全等方面
  • 可扩展架构:模块化设计,易于扩展和维护
  • 企业级应用:可直接应用于实际项目中

🌟 Lambda表达式的未来发展

🔮 技术发展趋势
  • Project Loom:虚拟线程将进一步提升Lambda表达式在并发编程中的价值
  • Pattern Matching:模式匹配将使函数式编程更加简洁和强大
  • Record Classes:记录类与Lambda表达式的结合将简化数据处理
  • Switch Expressions:增强的Switch表达式提供更多函数式编程选择
💼 企业应用前景
  • 微服务架构:Lambda表达式在事件驱动架构中的应用将更加广泛
  • 大数据处理:结合Stream API处理大规模数据的需求持续增长
  • AI/ML集成:函数式编程在机器学习管道中的应用前景广阔
  • 云原生应用:Serverless架构中Lambda表达式的重要性日益凸显
💡 实践建议
  • 从小项目开始:在现有项目中逐步引入Lambda表达式
  • 性能测试:始终关注性能影响,进行充分的基准测试
  • 代码审查:建立函数式编程的代码规范和审查标准
  • 团队培训:组织团队学习,提升整体技术水平
  • 持续重构:将传统代码逐步重构为函数式风格

通过本文的深入学习,相信您已经掌握了Lambda表达式在现代企业级应用中的高级用法。函数式编程不仅仅是一种编程范式,更是一种思维方式的转变。在未来的软件开发中,掌握这些技能将使您在技术道路上走得更远、更稳。


💡 持续学习:技术在不断发展,Lambda表达式和函数式编程的应用场景也在不断扩展。保持学习的热情,关注最新的技术动态,将这些先进的编程思想应用到实际项目中,创造更大的价值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值