[英]how can I verify if an String is already in a hashtable? java
我有以下情况:我试图遍历ArrayList
并将每个元素与HashTable
进行比较。 如果元素(字符串)相等,我想将其复制到新的HashTable
neu中 。 到这里为止一切顺利。 但是我想,如果该单词已经在新的HashTable
neu中 ,则不要再放它,只需简单地在代表频率的值中添加一个计数即可。 我想这段代码中永远不会到达else-block,因为它永远不会显示测试输出。 我知道在contentEquals
运作良好之前,它会向我返回所有相等的单词。
因此:如何验证HashTable
是否已存在字符串? 我希望它不会重复,我已经看到很多类似的问题,但是不知道如何在我的代码中正确使用它。
Hashtable<String, Long> neu = new Hashtable<String, Long>();
ArrayList<String> words = new ArrayList<String>();
Hashtable<String, Long> count = new Hashtable<String, Long>();
// adding input
for (String s : count.keySet()) {
for (String x : words) {
if (x.contentEquals(s)) {
if (!neu.containsKey(s)) {
neu.put(s, (long) 1);
} else {
long p = neu.get(s);
p = p + 1;
neu.put(s, p);
System.out.println("test");
}
}
}
输入如下:对于计数:
try {
BufferedReader in = new BufferedReader(new FileReader(
"griechenland_test.txt"));
String str;
while ((str = in.readLine()) != null) {
str = str.toLowerCase(); // convert to lower case
String[] words = str.split("\\s+"); // split the line on
// whitespace, would return
// an array of words
for (String word : words) {
if (word.length() == 0) {
continue;
}
Long occurences = wordcount.get(word);
if (occurences == null) {
occurences = (long) 1;
} else {
occurences++;
}
count.put(word, occurences);
}
}
对于单词:
BufferedReader br = new BufferedReader(new FileReader("outagain.txt"));
for (String line = br.readLine(); line != null; line = br.readLine()) {
String h[] = line.split(" ");
words.add(h[0].toString());
}
使用containsKey()
方法检查给定键是否已在哈希表中。
static Hashtable<String, Long> map = new Hashtable<String, Long>();
public static void main(String[] args)
{
map.put("test", 1l);
System.out.println(map.containsKey("test")); // true
}
对于字符串比较,请使用equals(Object)
或equalsIgnoreCase(String)
方法。
因此您的代码应如下所示:
for (String s : count.keySet())
{
for (String x : words)
{
if (x.equals(s))
neu.put(s, neu.containsKey(s) ? neu.get(s) + 1 : 1l);
}
}
请核实您的words
内容并count
。 这应该是问题所在,因为您的代码运行正常。
我可以解决! 我以为错误实际上是从输入开始的方式,那里没有重复,因此永远无法达到“其他”! 我只是消除了这种情况,并改变了结构。 无论如何,谢谢您的努力! :)
for (String x : hash.keySet()) {
long neu = hash.get(x);
for (String s : words) {
if (x.equals(s)) {
neuS.add(x);
neuZ.add(neu);
disc = disc + 1;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.