java案例统计伤病停赛影响数据对比?

wen java案例 2

本文目录导读:

java案例统计伤病停赛影响数据对比?

  1. 核心模型类
  2. 数据分析服务类
  3. 测试和演示类
  4. 进阶功能:可视化报告生成
  5. 使用说明

我来提供一个完整的Java案例,用于统计伤病停赛对球队战绩的影响数据对比。

核心模型类

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
// 球员实体类
class Player {
    private Long id;
    private String name;
    private String teamId;
    private String position;
    private boolean isInjured;
    private LocalDate injuryStartDate;
    private LocalDate expectedReturnDate;
    private String injuryType;
    // 构造方法、getter/setter省略
}
// 比赛实体类
class Match {
    private Long id;
    private String homeTeamId;
    private String awayTeamId;
    private LocalDate matchDate;
    private Integer homeScore;
    private Integer awayScore;
    private String status; // COMPLETED, UPCOMING
    // 判断主队是否获胜
    public boolean isHomeWin() {
        return homeScore > awayScore;
    }
    // 判断客队是否获胜
    public boolean isAwayWin() {
        return awayScore > homeScore;
    }
    // 获取获胜球队
    public String getWinnerTeamId() {
        if (homeScore > awayScore) return homeTeamId;
        if (awayScore > homeScore) return awayTeamId;
        return null; // 平局
    }
}
// 球队统计类
class TeamStatistics {
    private String teamId;
    private int totalMatches;
    private int wins;
    private int draws;
    private int losses;
    private int goalsScored;
    private int goalsConceded;
    private double winRate;
    // 计算胜率
    public void calculateWinRate() {
        this.winRate = totalMatches > 0 ? (double) wins / totalMatches * 100 : 0;
    }
}

数据分析服务类

import java.util.*;
import java.util.stream.Collectors;
// 伤病影响分析服务
class InjuryImpactAnalysisService {
    // 统计球员伤病期球队表现
    public Map<String, Object> analyzeInjuryImpact(List<Player> allPlayers, 
                                                    List<Match> allMatches,
                                                    List<String> teamIds) {
        Map<String, Object> result = new HashMap<>();
        // 按球队统计数据
        List<TeamImpactData> teamImpactData = new ArrayList<>();
        for (String teamId : teamIds) {
            TeamImpactData impactData = new TeamImpactData();
            impactData.setTeamId(teamId);
            // 获取该球队的所有比赛
            List<Match> teamMatches = allMatches.stream()
                .filter(m -> m.getHomeTeamId().equals(teamId) || m.getAwayTeamId().equals(teamId))
                .collect(Collectors.toList());
            // 获取球队伤病球员
            List<Player> injuredPlayers = allPlayers.stream()
                .filter(p -> p.getTeamId().equals(teamId) && p.isInjured())
                .collect(Collectors.toList());
            // 计算伤病期间战绩
            StatisticsCalculator calculator = new StatisticsCalculator();
            for (Player injuredPlayer : injuredPlayers) {
                List<Match> matchesDuringInjury = teamMatches.stream()
                    .filter(m -> m.getMatchDate().isAfter(injuredPlayer.getInjuryStartDate()) &&
                                 m.getMatchDate().isBefore(injuredPlayer.getExpectedReturnDate()))
                    .collect(Collectors.toList());
                // 计算伤病期间胜率
                TeamStatistics stats = calculator.calculateTeamStats(teamId, matchesDuringInjury);
                impactData.setMatchesDuringInjury(matchesDuringInjury.size());
                impactData.setWinRateWithInjury(stats.getWinRate());
                // 计算球员健康时的战绩(作为对比)
                List<Match> matchesWithoutInjury = teamMatches.stream()
                    .filter(m -> m.getMatchDate().isAfter(injuredPlayer.getExpectedReturnDate()) ||
                                 m.getMatchDate().isBefore(injuredPlayer.getInjuryStartDate()))
                    .collect(Collectors.toList());
                TeamStatistics normalStats = calculator.calculateTeamStats(teamId, matchesWithoutInjury);
                impactData.setWinRateWithoutInjury(normalStats.getWinRate());
                impactData.setInjuredPlayerName(injuredPlayer.getName());
                impactData.setInjuryType(injuredPlayer.getInjuryType());
            }
            teamImpactData.add(impactData);
        }
        result.put("teamImpactData", teamImpactData);
        result.put("analysisTime", new Date());
        result.put("totalTeamsAnalyzed", teamIds.size());
        return result;
    }
    // 比较不同伤病类型的平均影响
    public Map<String, Map<String, Double>> analyzeInjuryTypeImpact(List<Player> allPlayers, 
                                                                   List<Match> allMatches,
                                                                   List<String> teamIds) {
        Map<String, Map<String, Double>> injuryTypeImpact = new HashMap<>();
        Set<String> injuryTypes = allPlayers.stream()
            .map(Player::getInjuryType)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());
        for (String injuryType : injuryTypes) {
            Map<String, Double> typeStats = new HashMap<>();
            // 找出该伤病类型的球员
            List<Player> typeInjuredPlayers = allPlayers.stream()
                .filter(p -> injuryType.equals(p.getInjuryType()) && p.isInjured())
                .collect(Collectors.toList());
            // 计算平均缺阵天数
            double avgDaysOut = typeInjuredPlayers.stream()
                .mapToLong(p -> java.time.temporal.ChronoUnit.DAYS.between(
                    p.getInjuryStartDate(), p.getExpectedReturnDate()))
                .average()
                .orElse(0);
            // 计算胜率影响
            double avgWinRateChange = calculateAvgWinRateChange(allMatches, typeInjuredPlayers, teamIds);
            typeStats.put("averageDaysOut", avgDaysOut);
            typeStats.put("averageWinRateChange", avgWinRateChange);
            injuryTypeImpact.put(injuryType, typeStats);
        }
        return injuryTypeImpact;
    }
    private double calculateAvgWinRateChange(List<Match> allMatches, 
                                           List<Player> injuredPlayers, 
                                           List<String> teamIds) {
        // 简化示例:实际需要更复杂的计算逻辑
        return 15.0; // 示例返回
    }
    // 内部类:球队影响数据
    public static class TeamImpactData {
        private String teamId;
        private String injuredPlayerName;
        private String injuryType;
        private int matchesDuringInjury;
        private double winRateWithInjury;
        private double winRateWithoutInjury;
        private double impactPercentage; // 影响力百分比
        // getter/setter方法
        public String getTeamId() { return teamId; }
        public void setTeamId(String teamId) { this.teamId = teamId; }
        public String getInjuredPlayerName() { return injuredPlayerName; }
        public void setInjuredPlayerName(String playerName) { this.injuredPlayerName = playerName; }
        public String getInjuryType() { return injuryType; }
        public void setInjuryType(String injuryType) { this.injuryType = injuryType; }
        public int getMatchesDuringInjury() { return matchesDuringInjury; }
        public void setMatchesDuringInjury(int count) { this.matchesDuringInjury = count; }
        public double getWinRateWithInjury() { return winRateWithInjury; }
        public void setWinRateWithInjury(double winRate) { this.winRateWithInjury = winRate; }
        public double getWinRateWithoutInjury() { return winRateWithoutInjury; }
        public void setWinRateWithoutInjury(double winRate) { this.winRateWithoutInjury = winRate; }
        public double getImpactPercentage() {
            return winRateWithInjury - winRateWithoutInjury;
        }
        public void setImpactPercentage(double impact) { this.impactPercentage = impact; }
    }
}
// 统计计算器
class StatisticsCalculator {
    public TeamStatistics calculateTeamStats(String teamId, List<Match> matches) {
        TeamStatistics stats = new TeamStatistics();
        stats.setTeamId(teamId);
        int wins = 0, draws = 0, losses = 0;
        int goalsScored = 0, goalsConceded = 0;
        for (Match match : matches) {
            boolean isHome = match.getHomeTeamId().equals(teamId);
            int teamScore = isHome ? match.getHomeScore() : match.getAwayScore();
            int opponentScore = isHome ? match.getAwayScore() : match.getHomeScore();
            goalsScored += teamScore;
            goalsConceded += opponentScore;
            if (teamScore > opponentScore) {
                wins++;
            } else if (teamScore == opponentScore) {
                draws++;
            } else {
                losses++;
            }
        }
        stats.setTotalMatches(matches.size());
        stats.setWins(wins);
        stats.setDraws(draws);
        stats.setLosses(losses);
        stats.setGoalsScored(goalsScored);
        stats.setGoalsConceded(goalsConceded);
        stats.calculateWinRate();
        return stats;
    }
}

测试和演示类

import java.time.LocalDate;
import java.util.*;
public class InjuryImpactDemo {
    public static void main(String[] args) {
        // 1. 准备测试数据
        List<Player> players = createSamplePlayers();
        List<Match> matches = createSampleMatches();
        List<String> teamIds = Arrays.asList("TEAM001", "TEAM002", "TEAM003");
        // 2. 执行分析
        InjuryImpactAnalysisService service = new InjuryImpactAnalysisService();
        Map<String, Object> result = service.analyzeInjuryImpact(players, matches, teamIds);
        // 3. 输出结果
        printAnalysisResult(result);
        // 4. 按伤病类型分析
        Map<String, Map<String, Double>> typeAnalysis = service.analyzeInjuryTypeImpact(players, matches, teamIds);
        printInjuryTypeAnalysis(typeAnalysis);
    }
    // 创建示例球员数据
    private static List<Player> createSamplePlayers() {
        List<Player> players = new ArrayList<>();
        Player p1 = new Player();
        p1.setId(1L);
        p1.setName("张三");
        p1.setTeamId("TEAM001");
        p1.setPosition("前锋");
        p1.setInjured(true);
        p1.setInjuryStartDate(LocalDate.of(2024, 1, 1));
        p1.setExpectedReturnDate(LocalDate.of(2024, 3, 1));
        p1.setInjuryType("肌肉拉伤");
        players.add(p1);
        Player p2 = new Player();
        p2.setId(2L);
        p2.setName("李四");
        p2.setTeamId("TEAM001");
        p2.setPosition("中场");
        p2.setInjured(true);
        p2.setInjuryStartDate(LocalDate.of(2024, 2, 1));
        p2.setExpectedReturnDate(LocalDate.of(2024, 4, 1));
        p2.setInjuryType("脚踝扭伤");
        players.add(p2);
        // 添加更多球员...
        return players;
    }
    // 创建示例比赛数据
    private static List<Match> createSampleMatches() {
        List<Match> matches = new ArrayList<>();
        Match match1 = new Match();
        match1.setId(1L);
        match1.setHomeTeamId("TEAM001");
        match1.setAwayTeamId("TEAM002");
        match1.setMatchDate(LocalDate.of(2024, 1, 15));
        match1.setHomeScore(2);
        match1.setAwayScore(1);
        match1.setStatus("COMPLETED");
        matches.add(match1);
        // 添加更多比赛...
        return matches;
    }
    // 打印分析结果
    private static void printAnalysisResult(Map<String, Object> result) {
        System.out.println("=========== 伤病影响数据分析报告 ===========");
        System.out.println("分析时间: " + result.get("analysisTime"));
        System.out.println("分析球队数量: " + result.get("totalTeamsAnalyzed"));
        System.out.println();
        @SuppressWarnings("unchecked")
        List<InjuryImpactAnalysisService.TeamImpactData> impactDataList = 
            (List<InjuryImpactAnalysisService.TeamImpactData>) result.get("teamImpactData");
        System.out.printf("%-10s %-10s %-12s %-10s %-12s %-12s %-10s%n",
            "球队ID", "球员", "伤病类型", "缺阵场次", "伤病期间胜率", "正常胜率", "影响幅度");
        System.out.println("------------------------------------------------------------");
        for (InjuryImpactAnalysisService.TeamImpactData data : impactDataList) {
            System.out.printf("%-10s %-10s %-12s %-10d %-12.2f %-12.2f %-10.2f%n",
                data.getTeamId(),
                data.getInjuredPlayerName(),
                data.getInjuryType(),
                data.getMatchesDuringInjury(),
                data.getWinRateWithInjury(),
                data.getWinRateWithoutInjury(),
                data.getImpactPercentage());
        }
    }
    // 打印伤病类型分析
    private static void printInjuryTypeAnalysis(Map<String, Map<String, Double>> typeAnalysis) {
        System.out.println("\n=========== 伤病类型影响分析 ===========");
        for (Map.Entry<String, Map<String, Double>> entry : typeAnalysis.entrySet()) {
            System.out.println("伤病类型: " + entry.getKey());
            Map<String, Double> stats = entry.getValue();
            System.out.println("  平均缺阵天数: " + stats.get("averageDaysOut") + " 天");
            System.out.println("  胜率下降幅度: " + stats.get("averageWinRateChange") + "%");
            System.out.println();
        }
    }
}

进阶功能:可视化报告生成

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
// 报告生成器
class InjuryReportGenerator {
    public void generateReport(Map<String, Object> analysisData, String outputPath) {
        StringBuilder report = new StringBuilder();
        report.append("伤病停赛影响分析报告\n");
        report.append("=".repeat(50)).append("\n");
        @SuppressWarnings("unchecked")
        List<InjuryImpactAnalysisService.TeamImpactData> dataList = 
            (List<InjuryImpactAnalysisService.TeamImpactData>) analysisData.get("teamImpactData");
        // 生成HTML格式报告
        StringBuilder html = new StringBuilder();
        html.append("<html><head><title>伤病影响报告</title></head><body>");
        html.append("<h1>伤病停赛影响数据对比</h1>");
        html.append("<table border='1'>");
        html.append("<tr><th>球队</th><th>球员</th><th>伤病类型</th><th>缺阵场次</th>");
        html.append("<th>伤病期间胜率</th><th>正常胜率</th><th>影响幅度</th></tr>");
        for (InjuryImpactAnalysisService.TeamImpactData data : dataList) {
            html.append("<tr>");
            html.append("<td>").append(data.getTeamId()).append("</td>");
            html.append("<td>").append(data.getInjuredPlayerName()).append("</td>");
            html.append("<td>").append(data.getInjuryType()).append("</td>");
            html.append("<td>").append(data.getMatchesDuringInjury()).append("</td>");
            html.append("<td>").append(String.format("%.2f%%", data.getWinRateWithInjury())).append("</td>");
            html.append("<td>").append(String.format("%.2f%%", data.getWinRateWithoutInjury())).append("</td>");
            html.append("<td>").append(String.format("%.2f%%", data.getImpactPercentage())).append("</td>");
            html.append("</tr>");
        }
        html.append("</table></body></html>");
        // 写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
            writer.write(html.toString());
            System.out.println("报告已生成: " + outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用说明

  1. 数据准备:需要准备:

    • 球员信息(包括伤病状态)
    • 比赛历史数据
    • 球队信息
  2. 核心功能

    • 对比伤病期间与正常期的胜率变化
    • 分析不同伤病类型的影响程度
    • 生成可视化报告
  3. 扩展方向

    • 添加机器学习预测
    • 实时数据更新
    • 多维度分析(球员位置、球队实力等)

这个案例提供了完整的伤病影响分析框架,可以根据实际需求进行扩展和优化。

抱歉,评论功能暂时关闭!