簡體   English   中英

HashMap 字符串、字符串數組 - 如何在鍵中獲取某個索引?

[英]HashMap String, String Array - How do I get a certain index within a key?

    public class Main{
    final String filename = "stats.txt";
    List<String> lines = Files.readAllLines(Paths.get(filename)); //gets file, puts it in to listarray of strings.
    List<List<String>> playerInfo = new ArrayList<>(lines.size()); //creates new playerStats arraylist, Strings

    Scanner fs = new Scanner(new File(filename)); //opens file in scanner.
    int lineAmount;
    int quarters = 4;
    Random random = new Random();
    double randomNum;
    HashMap<String, String[]> playerData = new HashMap<String, String[]>();
    public Main() throws IOException {
        for (String line : lines) {
            String[] lineValues = line.split(",");
            playerInfo.add(Arrays.asList(lineValues));
            lineAmount++;
        }
        String playerVitals[][] = new String[lineAmount][7];
        String playerAttributes[][] = new String[lineAmount][19];
        for (int i = 0; i < lineAmount; i++) {
            playerVitals[i][0] = playerInfo.get(i).get(0); // Last Name
            playerVitals[i][1] = playerInfo.get(i).get(1); // First Name
            playerVitals[i][2] = playerInfo.get(i).get(2); // Position
            playerVitals[i][3] = playerInfo.get(i).get(3); // Secondary Position
            playerVitals[i][4] = playerInfo.get(i).get(4); // Height
            playerVitals[i][5] = playerInfo.get(i).get(5); // Weight
            playerVitals[i][6] = playerInfo.get(i).get(6); // Age

            playerAttributes[i][0] = playerInfo.get(i).get(7); //0 to 3 feet FGA
            playerAttributes[i][1] = playerInfo.get(i).get(8); // 3 to 10 feet FGA
            playerAttributes[i][2] = playerInfo.get(i).get(9); //10 to 16 feet FGA
            playerAttributes[i][3] = playerInfo.get(i).get(10); //16 feet to 3pt FGA
            playerAttributes[i][4] = playerInfo.get(i).get(11); //3pt FGA
            playerAttributes[i][5] = playerInfo.get(i).get(12); //0 to 3 feet FG
            playerAttributes[i][6] = playerInfo.get(i).get(13); //3 to 10 feet FG
            playerAttributes[i][7] = playerInfo.get(i).get(14); //10 to 16 feet FG
            playerAttributes[i][8] = playerInfo.get(i).get(15); //16 to 3pt FG
            playerAttributes[i][9] = playerInfo.get(i).get(16); //3pt FG
            playerAttributes[i][10] = playerInfo.get(i).get(17); //TOV%
            //playerAttributes[i][11] = playerInfo.get(i).get(18); //Athleticism
            //playerAttributes[i][12] = playerInfo.get(i).get(19); //Clutch
            playerAttributes[i][13] = playerInfo.get(i).get(20); //OReb%
            playerAttributes[i][14] = playerInfo.get(i).get(21); //Steal%
            playerAttributes[i][15] = playerInfo.get(i).get(22); //Block%
            playerAttributes[i][16] = playerInfo.get(i).get(23); //DReb%
            playerAttributes[i][17] = playerInfo.get(i).get(24); //Usage Rate
            playerAttributes[i][18] = playerInfo.get(i).get(25); //Overall Rating;

            playerData.put(playerVitals[i][0], new String[] {playerVitals[i][1], playerVitals[i][2], playerVitals[i][3], playerVitals[i][4], playerVitals[i][5], playerVitals[i][6],
                           playerAttributes[i][0], playerAttributes[i][1], playerAttributes[i][2], playerAttributes[i][3], playerAttributes[i][4], playerAttributes[i][5], playerAttributes[i][6], playerAttributes[i][7],
                           playerAttributes[i][8], playerAttributes[i][9], playerAttributes[i][10], playerAttributes[i][11], playerAttributes[i][12], playerAttributes[i][13], playerAttributes[i][14], playerAttributes[i][15],
                           playerAttributes[i][16], playerAttributes[i][17], playerAttributes[i][18]});
        }
        System.out.println(Arrays.toString(playerData.get(playerVitals[0][0])));
    }


    public static void main(String[] args) throws FileNotFoundException,IOException{
        new Main();
    }
}

我有這個代碼,它能夠加載一個文本 (csv) 文件並將其拆分為一個名為 playerInfo 的數組。 將其加載到 playerInfo 后,我創建了兩個名為 playerVitals 和 playerInfo 的二維數組。 將信息放在我想要的位置后,我創建了一個應該保存所有這些數據的哈希圖。 如您所見,hashmap 鍵是一個字符串,而 Hashmap 值是一個一維字符串數組。 如您所見,在那之后,我嘗試打印出數據以獲得某個點。 在這種情況下,例如,它將位於鍵“James”和索引 5 處。在我的電子表格中,這將與年齡匹配。 那么,對於關鍵的“James”和索引 5,我如何才能知道該球員此時的年齡是我的電子表格中的內容?

我對你的代碼做了一些清理。 有很多更改,因此最好查看新代碼,看看您是否可以了解更新的內容。 代碼中混有注釋來解釋更改。

對於這個問題,在您的原始代碼中,一旦您檢索了玩家的數據數組,年齡值將位於偏移量 6 處:

String lastName = playerVitals[0][0]; // For example
String[] onePlayerData = playerData.get(lastName);
String age = onePlayerData[6];

那是使用指示年齡存儲位置的注釋:

playerVitals[i][6] = playerInfo.get(i).get(6); // Age

在修改后的代碼中,下面的值將改為:

String lastName = "James"; // For example
String[] onePlayerVitals = allPlayerVitals.get(lastName);
String age = onePlayerVitals[6];

這是修改后的代碼:

package sample;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Renamed from the undescriptive 'Main':

public class PlayerDataStore {
    public static final String TEST_FILE_NAME = "stats.txt";

    public static void main(String[] args) throws FileNotFoundException,IOException {
        PlayerDataStore playerData = new PlayerDataStore();
        playerData.load(TEST_FILE_NAME);
        playerData.display();
    }

    // Names of the vitals and attributes.
    // Shifted from comments to usable data.
    // This is useful for displaying the values.

    private static String[] VITAL_NAMES = new String[] {
        "Last Name",
        "First Name",
        "Position",
        "Secondary Position",
        "Height",
        "Weight",
        "Age"
    };

    public static final int NUM_VITALS = VITAL_NAMES.length;

    private static String[] ATTR_NAMES = new String[] {
        "0 to 3 feet FGA",
        "3 to 10 feet FGA",
        "10 to 16 feet FGA",
        "16 feet to 3pt FGA",
        "3pt FGA",
        "0 to 3 feet FG",
        "3 to 10 feet FG",
        "10 to 16 feet FG",
        "16 to 3pt FG",
        "3pt FG",
        "TOV%",
        "Athleticism",
        "Clutch",
        "OReb%",
        "Steal%",
        "Block%",
        "DReb%",
        "Usage Rate",
        "Overall Rating"
    };

    public static final int NUM_ATTRS = ATTR_NAMES.length;

    //

    // Split the storage into separate 'vitals' and 'attributes' storage.
    // Putting both sets of data -- vitals, and attributes -- was a bit messy,
    // and seemed unnecessary.

    private Map<String, String[]> allPlayerVitals;
    private Map<String, String[]> allPlayerAttributes;

    // Moved static code, and other code which was under 'Main', to a descriptive method.

    // Unused values were removed.

    public void load(String filename) throws FileNotFoundException, IOException {
        // First load the line data, then process the data into the stores.

        // Note: Storing the line values into 'playerInfo' is not necessary:
        // The line values can be used directly to populate the vitals and
        // attributes.

        List<String> lines = Files.readAllLines( Paths.get(filename) );

        int lineAmount = lines.size();

        List<List<String>> playerInfo = new ArrayList<>(lineAmount);

        for ( String line : lines ) {
            String[] lineValues = line.split(",");
            playerInfo.add( Arrays.asList(lineValues) );
        }

        // Make space for the vitals and attributes ...

        allPlayerVitals = new HashMap<String, String[]>( lineAmount );
        allPlayerAttributes = new HashMap<String, String[]>( lineAmount );

        // Transfer data from the vitals and attributes into storage ...

        for ( List<String> nextInfo : playerInfo ) {
            String playerVitals[] = new String[NUM_VITALS];

            for ( int vitalNo = 0; vitalNo < NUM_VITALS; vitalNo++ ) {
                playerVitals[vitalNo] = nextInfo.get(vitalNo);
            }

            // 'playerVitals[0]' is the players last name, which is currently
            // a unique value.
            //
            // TODO: The uniqueness of the player last name seems overly
            //       optimistic.  A different key value may be needed

            allPlayerVitals.put( playerVitals[0], playerVitals );

            String playerAttributes[] = new String[19];

            for ( int attrNo = 0; attrNo < 19; attrNo++ ) {
                if ( (attrNo == 11) || (attrNo == 12) ) {
                    continue;
                }
                playerAttributes[attrNo] = nextInfo.get(NUM_VITALS + attrNo);
            }

            // Store the attributes using the player last name.

            allPlayerAttributes.put( playerVitals[0], playerAttributes );
        }
    }

    void display() {
        // Display all stored data.

        // Note: The order of entries is random, since it is an iteration across a
        //       hash mapping.

        for ( Map.Entry<String, String[]> vitalsEntry : allPlayerVitals.entrySet() ) {
            String playerLastName = vitalsEntry.getKey();
            String[] playerVitals = vitalsEntry.getValue();

            String[] playerAttributes = allPlayerAttributes.get(playerLastName);

            for ( int vitalNo = 0; vitalNo < playerVitals.length; vitalNo++ ) {
                System.out.println("[ " + vitalNo + " ] " + VITAL_NAMES[vitalNo] + ": " + playerVitals[vitalNo] );
            }

            for ( int attrNo = 0; attrNo < playerAttributes.length; attrNo++ ) {
                if ( (attrNo == 11) || (attrNo == 12) ) {
                    continue;
                }
                System.out.println("[ " + attrNo + " ] " + ATTR_NAMES[attrNo] + ": " + playerAttributes[attrNo] );
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM