Java 将字符添加到映射,具体取决于它们是否已存在



我正在为学校做作业,这需要我编写一个算法来放置一个键(在本例中为字符类型(和一个递增 1 的值,然后作为递增值放回映射中。但是,如果当前字符不存在,我应该放置键值对"current_character,1"。此方法只是向映射添加一个新条目,并且不会递增该值(假设它是同类中的第一个(。这是代码:

 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()

以下是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

老实说,我在这里最大的问题是,"这是否正确地将元素添加到地图中?我已经调试了一段时间,并且无法看到为什么我的输出如此奇怪的问题。我可以附加我的输出,但我还必须包含相当多的代码才能理解它发生的事情,所以我想(因为这是我的主要问题(,我只会包含这段代码。

是的,它可以正常工作,尽管您可以简化:

int val = charCountAlpha.get( currentKey );
val++; // add 1 to val
charCountAlpha.put( currentKey, val );

跟:

charCountAlpha.put( currentKey, charCountAlpha.get(currentKey)+1);

此外,可能没有必要使用 TreeMap 如果您有已知的键集(例如英语字母(,您可以使用HashMap来获得更好的时间复杂度。

相关内容

最新更新