在Java中的HashMap中为键添加两个值

时间:2016-04-03 00:52:44

标签: java hashmap key

我使用的文件包含:

"word","wordtype","definition"

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

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

输出如下:

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."]

期望的结果:

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

有人能指出我正确的方向吗?

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

            }

1 个答案:

答案 0 :(得分:1)

Map无法按您的要求运作。任何key只能映射到一个value

如果您想要类似某些内容,但您可以为给定的values提供多个key,则可以执行以下操作:

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

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

然后遍历您的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())));
}

编辑:

对于您的评论:如果您需要,可以随时滚动自己的类型以存储在Map(如果您仍需要重复密钥,则为List):

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

并在List<Map.Entry<String, WordDescription>>中使用它。如果有wordType enum预先定义的一组(形容词,名词等),则可以 function HdweTick: longint; assembler; asm RDTSC movl %eax,__result end;