[英]Counting occurrences of string in an arraylist using case-insensitive comparison
我必须计算包含字符串和整数的ArrayList
中每个String
的出现次数。 现在,我必须忽略与每个项目的数量相对应的int
变量,而只计算该列表中每个String的重复次数。
我的问题是,在课堂上我们只使用int做此操作。 现在使用Strings时,我遇到了一个问题,因为“ 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的Abc”,然后在input.txt文件列表中,我出现了4次相同的出现-“ abc的Abc”; “ Abc的abc”; “ Abc of Abc”和“ abc Of abc”-均以不同的方式书写,并且分别对它们进行计数,而不是对同一事件进行4次计数。
早些时候,当我计算总计和平均值时,我可以使用equalsIgnoreCase()
使其在其中正常工作,因此无论大小写如何,它都将它们计入正确的列表中,而不是将其计为一次。
有没有一种方法可以在忽略它们之前使用忽略大小写或将所有内容转换为相同的大小写?
只是一个更新 :不要试图在.toLowerCase()
有,我用它在FileReader
时,它读取.txt文件和它的工作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);
}
}
}
HashMap的哈希函数区分大小写,因此您需要将字符串值大写或小写。 请参阅下面的修改后的代码:
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.toString(). toLowerCase() , (count.intValue() + 1));
}
for (Map.Entry<String, Integer> entry : getCount1.entrySet())
f.println(entry.getKey() + " : " + entry.getValue());
}
出于风格考虑,我将为ItemsList中的项目(如item
使用更具描述性的名称。
我没有尝试.toLowerCase()
,而是在FileReader
使用它在读取.txt文件并且可以正常工作时使用它i.name = name.toLowerCase();
所以最后我的代码是这样的:
static void readFile(ArrayList<Items> list) throws IOException {
BufferedReader in = new BufferedReader(
new FileReader("input.txt")
);
String text;
while( (text = in.readLine()) != null ) {
if(text.length()==0) break;
Scanner line = new Scanner(text);
linha.useDelimiter("\\s*:\\s*");
String name = line.next();
int qtt = line.nextInt();
Items i = new Items();
i.name = name.toLowerCase();
i.qtt = qtt;
list.add(i);
}
in.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.