java案例怎么看两队拦截抢断数据?

wen java案例 5

本文目录导读:

java案例怎么看两队拦截抢断数据?

  1. 方案一:数据在Java对象(如List或Map)中(最常用)
  2. 方案二:数据来自数据库(JDBC/MyBatis/JPA)
  3. 方案三:数据来自RESTful API(如体育数据平台)
  4. 方案四:文件数据(CSV/Excel)解析
  5. 高效对比展示的可视化方案
  6. 如何选择

在Java中查看两队拦截和抢断数据,具体方法取决于数据来源(数据库、API接口、文件、内存对象等),下面是几种常见场景的解决方案和代码示例:


数据在Java对象(如List或Map)中(最常用)

假设你已经从某个数据源加载了比赛数据,存储在Java对象中。

定义实体类

public class PlayerStats {
    private String teamName;
    private String playerName;
    private int interceptions; // 拦截
    private int steals;        // 抢断
    // 构造函数、getter/setter 省略
    // 用IDE生成(Alt+Insert)
}

使用Java 8 Stream API进行聚合统计

import java.util.*;
import java.util.stream.Collectors;
public class StatsAnalyzer {
    public static void main(String[] args) {
        // 模拟数据(通常来自数据库查询或API)
        List<PlayerStats> allStats = Arrays.asList(
            new PlayerStats("湖人", "詹姆斯", 1, 2),
            new PlayerStats("湖人", "戴维斯", 3, 1),
            new PlayerStats("勇士", "库里", 2, 1),
            new PlayerStats("勇士", "格林", 4, 3)
        );
        // 按球队分组统计
        Map<String, TeamAggregate> teamStats = allStats.stream()
            .collect(Collectors.groupingBy(
                PlayerStats::getTeamName,
                Collectors.collectingAndThen(
                    Collectors.toList(),
                    list -> {
                        int totalInterceptions = list.stream()
                            .mapToInt(PlayerStats::getInterceptions).sum();
                        int totalSteals = list.stream()
                            .mapToInt(PlayerStats::getSteals).sum();
                        return new TeamAggregate(totalInterceptions, totalSteals);
                    }
                )
            ));
        // 输出两队对比
        teamStats.forEach((team, stat) -> {
            System.out.printf("球队: %s | 总拦截: %d | 总抢断: %d%n",
                team, stat.totalInterceptions, stat.totalSteals);
        });
    }
    // 辅助类
    static class TeamAggregate {
        int totalInterceptions;
        int totalSteals;
        TeamAggregate(int interceptions, int steals) {
            this.totalInterceptions = interceptions;
            this.totalSteals = steals;
        }
    }
}

数据来自数据库(JDBC/MyBatis/JPA)

使用JDBC直接查询(按球队聚合)

import java.sql.*;
public class DbStats {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/basketball";
        String user = "root";
        String password = "password";
        String sql = """
            SELECT team_name, 
                   SUM(interceptions) AS total_interceptions,
                   SUM(steals) AS total_steals
            FROM player_match_stats
            WHERE match_id = ?
            GROUP BY team_name
            """;
        try (Connection conn = DriverManager.getConnection(url, user, password);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, 20241001); // 比赛ID
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                String team = rs.getString("team_name");
                int interceptions = rs.getInt("total_interceptions");
                int steals = rs.getInt("total_steals");
                System.out.println("球队: " + team + " | 拦截: " + interceptions + " | 抢断: " + steals);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

使用Spring JdbcTemplate(更简洁)

@Repository
public class StatsRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<TeamStats> getTeamStats(int matchId) {
        String sql = """
            SELECT team_name, 
                   SUM(interceptions) AS interceptions,
                   SUM(steals) AS steals
            FROM player_match_stats
            WHERE match_id = ?
            GROUP BY team_name
            """;
        return jdbcTemplate.query(sql, 
            new Object[]{matchId},
            (rs, rowNum) -> new TeamStats(
                rs.getString("team_name"),
                rs.getInt("interceptions"),
                rs.getInt("steals")
            ));
    }
}

数据来自RESTful API(如体育数据平台)

使用HttpClient调用API并解析JSON

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ApiStatsFetcher {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.sportsdata.io/v3/nba/stats/json/BoxScore/20241001"))
            .header("Ocp-Apim-Subscription-Key", "YOUR_API_KEY")
            .build();
        HttpResponse<String> response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(response.body());
        // 遍历两队数据
        root.get("Games").forEach(game -> {
            String homeTeam = game.get("HomeTeam").asText();
            String awayTeam = game.get("AwayTeam").asText();
            // 根据具体API结构提取拦截和抢断数据
            System.out.println(homeTeam + " vs " + awayTeam);
        });
    }
}

文件数据(CSV/Excel)解析

// 使用Apache Commons CSV
import org.apache.commons.csv.*;
public class CsvStatsReader {
    public static void main(String[] args) throws Exception {
        Reader in = new FileReader("match_stats.csv");
        Iterable<CSVRecord> records = CSVFormat.DEFAULT
            .withHeader("player","team","interceptions","steals")
            .parse(in);
        Map<String, List<Integer>> teamStats = new HashMap<>();
        for (CSVRecord record : records) {
            String team = record.get("team");
            int interceptions = Integer.parseInt(record.get("interceptions"));
            int steals = Integer.parseInt(record.get("steals"));
            teamStats.computeIfAbsent(team, k -> new ArrayList<>())
                     .addAll(Arrays.asList(interceptions, steals));
        }
        // 输出聚合结果
        teamStats.forEach((team, values) -> {
            int totalInterceptions = values.stream().mapToInt(Integer::intValue).sum();
            // 注意:这里逻辑需按列分开统计,示例仅为演示
        });
    }
}

高效对比展示的可视化方案

如果想在控制台或GUI中直观对比,可以这样设计:

public class ComparisonView {
    public static void printComparison(TeamStats home, TeamStats away) {
        System.out.println("========================================");
        System.out.printf("%-15s %-10s %-10s%n", "球队", "拦截", "抢断");
        System.out.println("----------------------------------------");
        System.out.printf("%-15s %-10d %-10d%n", 
            home.teamName, home.interceptions, home.steals);
        System.out.printf("%-15s %-10d %-10d%n", 
            away.teamName, away.interceptions, away.steals);
        System.out.println("========================================");
        // 简单胜负判断
        String winner = (home.interceptions + home.steals) > 
                        (away.interceptions + away.steals) 
                        ? home.teamName : away.teamName;
        System.out.println("防守数据占优球队: " + winner);
    }
}

如何选择

数据来源 推荐方式
内存对象/集合 Java Stream API + Collectors.groupingBy
关系型数据库 SQL GROUP BY + 聚合函数(最推荐)
API接口 HttpClient + JSON解析(如Jackson)
CSV/Excel文件 Apache POI 或 Commons CSV

核心思路:先确定数据在哪个“容器”里,然后用对应的聚合方式(SQL或Java Stream)按球队分组,SUM拦截和抢断字段即可。

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