如何使用字符串数组作为哈希映射中的键?

How can I use a string array as key in hash map?

我已经用 .txt 创建了一个字符串数组,现在想创建一个以此字符串为键的 HashMap。但我不想让字符串作为一个值的一个键,我想让每个信息作为 HashMap 的一个新键。

private static String[] readAndConvertInputFile() {
String str = StdIn.readAll();
String conv = str.replaceAll("\'s", "").replaceAll("[;,?.:*/\-_()\"\'\n]", " ").replaceAll(" {2,}", " ").toLowerCase();
return conv.split(" ");  }

所以字符串中的信息就像("word", "thing", "etc.", "pp.", "thing").

我的值应该是单词在文本中出现的频率。因此,例如 key: "word" value: 1, key: "thing" value: 2 等等......我很无能,如果有人能帮助我,至少用钥匙,我将不胜感激。 :)

您可以创建一个 Map,同时使用每个 array 索引处的 String 值作为键,并使用 Integer 作为值来跟踪如何一个词出现了很多次。

Map<String,Integer> map = new HashMap<String,Integer>();

然后当你想自增的时候,你可以检查Map是否已经包含了这个key,如果有就加1,否则就设置为1。

if (occurences.containsKey(word)) {
    occurences.put(word, occurences.get(word) + 1);
} else {
    occurences.put(word, 1);
}

因此,当您遍历字符串数组时,将 String 转换为小写(如果您想忽略单词出现的大小写),并使用 if 语句递增映射以上。

for (String word : words) {
    word = word.toLowerCase(); // remove if you want case sensitivity
    if (occurences.containsKey(word)) {
        occurences.put(word, occurences.get(word) + 1);
    } else {
        occurences.put(word, 1);
    }
}

完整示例如下所示。在地图中使用键时,我将单词转换为小写以忽略大小写,如果要保留大小写,请删除我将其转换为小写的行。

public static void main(String[] args) {

    String s = "This this the has dog cat fish the cat horse";
    String[] words = s.split(" ");
    Map<String, Integer> occurences = new HashMap<String, Integer>();

    for (String word : words) {
        word = word.toLowerCase(); // remove if you want case sensitivity
        if (occurences.containsKey(word)) {
            occurences.put(word, occurences.get(word) + 1);
        } else {
            occurences.put(word, 1);
        }
    }

    for(Entry<String,Integer> en : occurences.entrySet()){
        System.out.println("Word \"" + en.getKey() + "\" appeared " + en.getValue() + " times.");
    }

}

这将给我输出:

Word "cat" appeared 2 times.
Word "fish" appeared 1 times.
Word "horse" appeared 1 times.
Word "the" appeared 2 times.
Word "dog" appeared 1 times.
Word "this" appeared 2 times.
Word "has" appeared 1 times.

是的,您可以使用数组(无论元素类型如何)作为HashMap键。

不,不应该这样做。该行为不太可能是您想要的(一般情况下)。

在你的具体情况下,我不明白你为什么一开始就建议使用数组作为键。您似乎希望从数组元素中抽取 Strings 作为键。

您可以像这样构造词频 table:

Map<String, Integer> computeFrequencies(String[] words) {
    Map<String, Integer> frequencies = new HashMap<String, Integer>();

    for (String word: words) {
        Integer wordFrequency = frequencies.get(word);

        frequencies.put(word,
                (wordFrequency == null) ? 1 : (wordFrequency + 1));
    }

    return frequencies;
}

在java 8 使用流

String[] array=new String[]{"a","b","c","a"};
Map<String,Integer> map1=Arrays.stream(array).collect(Collectors.toMap(x->x,x->1,(key,value)->value+1));