简体   繁体   中英

Adding two values to a key in a HashMap in Java

I am using a file that consists of:

"word","wordtype","definition"

"Base","n.","The lower part of a robe or petticoat."

"Base","n.","An apron."

The output is as follows:

key: "base" value: ["word""wordtype""definition", "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."] key: "word" value: ["word""wordtype""definition", "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]

Desired outcome:

key: "base" value: [ "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."] key: "word" value: ["word""wordtype""definition"]

Can someone point me in the right direction?

BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(file)));

    String line = null;

    TreeMap<String, List<String>> def = new TreeMap<String, List<String>>();
    List<String> values = new ArrayList<String>();

        try {
            while ((line = br.readLine()) != null) {
                String []parts =line.split(",");
                String key = null;
                for (int i = 0; i < parts.length; i++){
                    key = parts[0];
                }

                values.add(parts[0] + parts[1] + parts[2]);
                def.put(key.toLowerCase(), values);

            }

A Map cannot work as you request. Any key can only be mapped to a single value .

If you want something akin to what you're doing, but where you can have multiple values for a given key , you could do something like:

List<Map.Entry<String, List<String>>> def = new ArrayList<>();

Map.Entry<String, List<String>> entry = new AbstractMap.SimpleEntry<>(key, list);
def.add(entry);

Then iterate through your def :

for (Map.Entry<String, List<String>> entry : def) {
    System.out.println(String.format("Key: %s.  Values: %s",
            entry.getKey(),
            Arrays.toString(entry.getValue().toArray())));
}

Edit:

For your comment: If you want that, you can always roll your own type to store in the Map (or List if you still need duplicate keys):

class WordDescription {
    final String wordType;
    final String definition;

    WordDescription(String wordType, String definition) {
        this.wordType = wordType;
        definition = definition;
    }

    String getWordType() {
        return wordType;
    }

    String getDefinition() {
        return definition;
    }
}

And use that in a List<Map.Entry<String, WordDescription>> . You can make wordType an enum if there's a pre-defined set of them (adjective, noun, etc.).

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