我有一个 ArrayList
,用户可以通过输入“1”来填充字符串,然后在程序运行时输入字符串:
ArrayList<String> inStrings = new ArrayList<String>();
//(I left out the main while)
if (programCTRL == 1) {
System.out.println("Enter your keyword!");
inStrings.add(scan.nextLine());
System.out.println(inStrings);
}
当用户按 2 时,他们应该收到某个单词重复的次数。重复的字符串不必彼此相邻。例如。如果用户输入“Bear”三次,“Owl”两次,一次“Cat”,则输出应如下所示:
Bear - 3.
Owl - 2.
Cat - 1.
我该怎么做?
最佳答案
使用相同的ArrayList
,无需任何其他支持结构,您可以对元素进行排序:
Collections.sort(inStrings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2); // if you don't care about uppercase and lowercase;
}
});
然后在 foreach 循环中,您可以计算每个元素出现的次数:
String lastElement = null;
int counter = 0;
for(String s : inStrings){
if(lastElement == null){
lastElement = s;
counter = 1;
continue;
}
if(!s.equals(lastElement)){
System.out.println(lastElement + ": " + counter);
lastElement = s;
counter = 1;
}
else
counter++;
}
if(lastElement != null)
System.out.println(lastElement + ": " + counter);
关于java - 如何计算ArrayList中重复单词的数量(不使用Hash),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665291/