Java根据字符是否已存在向映射添加字符
我正在为学校做一项作业,这要求我编写一个算法,将一个键(在本例中为字符类型)和一个递增1的值作为递增值放回地图中。 但是,如果当前字符不存在,我应该放置“current_character,1”的键值对。此方法只是向映射中添加一个新条目,而不增加值(假设它是同类中的第一个)。 代码如下:Java根据字符是否已存在向映射添加字符,java,syntax,Java,Syntax,我正在为学校做一项作业,这要求我编写一个算法,将一个键(在本例中为字符类型)和一个递增1的值作为递增值放回地图中。 但是,如果当前字符不存在,我应该放置“current_character,1”的键值对。此方法只是向映射中添加一个新条目,而不增加值(假设它是同类中的第一个)。 代码如下: private void calculateCharCountAlpha(){ for(String current : lines){ for(int i = 0, length =
private void calculateCharCountAlpha(){
for(String current : lines){
for(int i = 0, length = current.length(); i < length; i++){ // iterate through each character of each string
char currentKey = current.charAt(i);
if(! (charCountAlpha.containsKey( currentKey )) ){ // check if the map doesn't contain the current character at the current location in the current string
charCountAlpha.put( currentKey, 1 ); // place the current character into the map, with a value of 1
} // end of if
else{
int val = charCountAlpha.get( currentKey );
val++; // add 1 to val
charCountAlpha.put( currentKey, val ); // place the current character in the map, with a value that has been added to 1
} // end of else
} // end of for
} // end of for-each
/** Call calculateCharCountDescendingByCount */
calculateCharCountDescendingByCount();
} // end of calculateCharCountAlpha()
private void calculateCharCountAlpha(){
用于(串电流:线){
对于(int i=0,length=current.length();i
这里是charCountAlpha:
private TreeMap< Character, Integer > charCountAlpha = new TreeMap<>(); // this map stores the number of words, with their counts. Also stores the elements in order of key
private TreeMapcharCountAlpha=new TreeMap();//此映射存储单词数及其计数。还按键的顺序存储元素
老实说,我最大的问题是,“这是否正确地将元素添加到地图?”。我已经调试了一段时间,但还没有看到为什么我的输出如此奇怪的问题。我可以附加我的输出,但我还必须包含更多的代码来理解它发生了什么,所以我想(因为这是我的主要问题),我只需要包含这些代码。是的,它工作正常,但您可以简化:
int val = charCountAlpha.get( currentKey );
val++; // add 1 to val
charCountAlpha.put( currentKey, val );
与:
此外,如果您有一个已知的键集(例如英语字母表),则可能不需要使用
TreeMap
,您可以使用HashMap
来获得更好的时间复杂度。在我看来很好如果您不确定,可以尝试打印地图,看看它是否正确。我觉得你的代码还可以。如果您在找出输出错误的原因时遇到问题,请发布不同的问题并包含代码的这一部分。
charCountAlpha.put( currentKey, charCountAlpha.get(currentKey)+1);