我用.txt创建了一个String数组,现在想用这个字符串作为键来创建一个HashMap。但是我不希望将String作为一个值的一个键,我希望将每个Information作为HashMap的新键。
private static String[] readAndConvertInputFile() {
String str = StdIn.readAll();
String conv = str.replaceAll("\'s", "").replaceAll("[;,?.:*/\\-_()\"\'\n]", " ").replaceAll(" {2,}", " ").toLowerCase();
return conv.split(" "); }
所以字符串中的信息就像("字","事物","等等。"," pp。&#34 ;,"事情")。
我的值应该是文本中单词的频率。所以例如关键:" word"值:1,关键:"事物"价值:2等等......我很无能为力,如果有人可以帮助我,我会很感激,至少用钥匙。 :)
答案 0 :(得分:2)
您可以使用每个Map
索引处的String
值作为关键字创建array
,并使用Integer
作为值来跟踪多少次一句话出现了。
Map<String,Integer> map = new HashMap<String,Integer>();
然后,当您想要增加时,可以检查Map
是否已包含密钥,如果是,则将其增加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.
答案 1 :(得分:1)
是的,您可以使用数组(无论元素类型如何)作为HashMap
键。
不,不应该这样做。这种行为不太可能是你想要的(通常)。
在您的特定情况下,我不明白为什么您甚至建议首先使用数组作为键。您似乎希望从数组元素中抽取String
作为键。
您可以像这样构建一个单词频率表:
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;
}
答案 2 :(得分:0)
在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));