简体   繁体   中英

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();
    }
}

I have this code, which is able to load in a text (csv) file and split it into an array named playerInfo. After loading it into playerInfo, I create a two 2d arrays named playerVitals and playerInfo. After putting the information where I want them, I create a hashmap which is supposed to hold all of this data. As you can see, the hashmap key is a String and the Hashmap value is a 1d String array. As you can see, after that, I try to print out the data to get at a certain point. In this case, it would be at, for example, the key "James" and at the index 5. On my spreadsheet, that would match up with age. So how would, for the key "James" and the index 5, I get that this player's age at this point is what is in my spreadsheet?

I did a bit of clean-up on your code. There were a lot of changes, so it would be best to review the new code and see if you can get an understanding of what was updated. There are comments mixed in with the code to explain the changes.

For the question, in your original code, once you've retrieved the array of data for a player, the age value is at offset 6:

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

That is using the comment that indicated where the age was stored:

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

In the modified code, below, the value would be obtained instead as:

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

Here is the modified code:

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] );
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM