Generating a hash map with multiple tokens

I have the following text file

0 name1 name2 name3 name4 vs. name11 name22 name33 name44
1 name1 name2 name3 name4 vs. name11 name22 name33 name44 

      

I want to keep 0, name1 through 4 and name11 through name44

.

The program I am doing tells me which team won. If the first integer is 0 then name11 through name44 will win and vice versa

Am I stuck on how to make multiple tokens?

This is what I have so far:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Winning {

    public static int whoWon(String filename) {
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader in = null;
        try {
            String line = "";
            in = new BufferedReader(new FileReader(filename));
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                String parts[] = line.split(" ");
                map.put(parts[0], parts[1]);
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(map.toString());

        return 0;
    }

    public static void main(String[] args) {
        Stats s = new Stats();
        s.wins("filepath/filename.txt");
    }
}

      

+3


source to share


3 answers


The map can of course store the collection as a value, so you can do something like this ...



Map<String, List<String>> map = new HashMap<String, List<String>>();
...
List<String> list = new ArrayList<String>();
list.add(parts[1]);
...add all tokens to list
map.put(parts[0], list);

      

+2


source


You can use Map<String, List<String>> map

orMap<String, String[]> map



+1


source


I would suggest making a dto like Team

in which you can store the command data like the names of the team members.

Then you can do another dto like Match

where you can store team1, team2 and boolean that the team won.

And then you can create list

of Match

where you can put each line of the text file.

If the first integer is 0, then name11 by name44 will win and vice versa , so I think you will have multiple lines with value as 0 as well as 1.

So I don't see a map use case in your case.

0


source







All Articles