gpt4 book ai didi

java - 使用不区分大小写的比较来计算数组列表中字符串的出现次数

转载 作者:行者123 更新时间:2023-12-01 17:17:07 27 4
gpt4 key购买 nike

我必须计算包含字符串和整数的 ArrayList 中每个 String 的出现次数。现在,我必须忽略与每个项目的数量相对应的 int 变量,而只计算该列表中每个字符串的重复次数。

我的问题是在类里面我们只用整数来做这个。现在,对于字符串,我遇到了大小写问题,因为“abc”与“Abc”不同,“def of Ghi”与“Def of ghi”不同。

现在我的代码是这样的:

Map<String, Integer> getCount1 = new HashMap<>();
{
for (ItemsList i : list) {
Integer count = getCount1.get(i.name);
if (count == null) {
count = 0;
}
getCount1.put(i.name, (count.intValue() + 1));
}

for (Map.Entry<String, Integer> entry : getCount1.entrySet())
f.println(entry.getKey() + " : " + entry.getValue());
}

但正如我所说:它没有正确计算出现次数。例如,我的列表中出现了一次名为“Abc of abc”的情况,然后在 input.txt 文件列表中出现了 4 次相同的情况 - “Abc of abc”; “ABC 的ABC”; “Abc of Abc”和“abc Of abc” - 写法都不同,并且分别对它们进行计数,而不是对相同的出现进行 4 次计数。

早期,当我处理总计和平均值时,我能够使用equalsIgnoreCase(),因此它在那里工作得很好,所以无论大小写如何,它都会将它们计数在正确的列表中,但是不只是一次出现多次。

有没有办法可以在计数之前使用忽略大小写或将所有内容转换为相同的大小写?

只是一个更新:当它读取.txt文件时,我在FileReader中使用它,而不是尝试.toLowerCase()它有效 i.name = name.toLowerCase();

无论如何,感谢您的时间和帮助

最佳答案

试试这个:

public void getCount(){
Map<String, Integer> countMap = new HashMap<String, Integer>();
for(ItemsList i : itemsList){
if(countMap.containsKey(i.Name.toLowerCase())){
countMap.get(i.Name.toLowerCase())++;
}
else{
countMap.put(i.Name.toLowerCase(),1);
}
}
}

关于java - 使用不区分大小写的比较来计算数组列表中字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234341/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com