patski
patski

Reputation: 329

adding Strings to HashMap

I'm trying to put some Strings to a HashMap, but they wont add. My code looks like this and I can't seem to understand why they won't add. Can someone help me and give me an explanation to what I'm doing wrong?

HashMap <String, String> akro = new HashMap <String, String>();

public void lesFil() {
    try {
        BufferedReader br = new BufferedReader(new FileReader("akronymer.txt"));
        String line;

        while((line = br.readLine()) != null) {
            if(!line.contains(" ")) {
                continue;
            }
            String[] linje = line.split("\\s+", 2);

            String akronym = linje[0];
            String betydning = linje[1];

//              System.out.println(a + " || " + b);
            akro.put(akronym, betydning);
        }
    } catch(Exception e) {
        System.out.println("Feilen som ble fanget opp: " + e);
    }
}

When I'm removing "//", both akronym and betydning prints out fine.

I tried to add this method to test the HashMap but nothing prints out and the size = 0

public void skrivUt() {
    for(Map.Entry <String, String> entry : akro.entrySet()) {
        System.out.print("Key: " + entry.getKey());
        System.out.println(", Value: " + entry.getValue());

    }
    System.out.println("Antall akronymer: " + akro.size());
}   

Part of the file I'm reading from(txt file):

...
CS        Chip Select  
CS Clear to Send  
CS Code Segment
C/S       Client/Server
...

Upvotes: 2

Views: 853

Answers (1)

Todd
Todd

Reputation: 31720

Remember that a Map in Java maps one key to one value. In the sample data you provide, it seems that you have multiple values ("Chip Select", "Clear to Send", "Code Segment") for one key ("CS").

You can solve this by either picking a structure other than a Map, changing what you want to store, or changing the value of the Map to a List<String>.

For example:

List<String> values = akro.get(akronym);
if(values == null) {
   values = new LinkedList<String>();
   akro.put(akronym, values);
}
values.add(betydning);

Upvotes: 3

Related Questions