Creating an unordered map of <char, int> in java

梦想的初衷 提交于 2019-12-05 10:03:38

Try this declaration:

Map<Character, Integer> m = new HashMap<Character, Integer>();

You can then add characters as such:

char c = //...;
if (m.containsKey(c))
    m.put(c, m.get(c) + 1);
else
    m.put(c, 1);

I would implement it using int[] (for ASCII) or int[][] for unicode. Given the memory footprint of storing boxed integers in a hash map with all the hashing conflicts introduced by using numbers, and characters are nothing but numbers, as keys.

public class CharacterBag {

    private int[][] data = new int[255][];

    public void add(char ch) {
        int[] bin = data[ch >> 8];
        if (bin == null) bin = data[ch >> 8] = new int[255];
        bin[ch & 0xFF]++;
    }

    public int frequency(char ch) {
        int[] bin = data[ch >> 8];
        if (bin == null) return 0;
        return bin[ch & 0xFF];
    }

}

This starts with a memory footprint of zero, and adds 2K for each unicode page. Typically text uses characters from one or two unicode pages.

In comparison using HashMap will have the whole overhead of storing boxed primitives in a list of linked lists. For each character there will an object of the Entry class with two pointers pointing to a boxed key and a linked list object with all its fields and which holds an object of class Node with a forward and a backward pointer and which has a pointer to the boxed integer … shall I go on? ;)

Map<Character, Integer> charCount = new HashMap<Character, Integer>();

public void addCharacter(char c) {
    Integer value = charCount.get(c);
    if (value == null) {
        charCount.put(c, 1);
    } else {
        charCount.put(c, value + 1);
    }
}

Java collections does not allow you to create a collection of primitive types, rather you should use their respective wrapper class (eg The wrapper class for int is Integer).

Map<Character,Integer> hashMap = new HashMap<Character,Integer>();

This how you declare a map. for more examples and explanation please look here

Best way according to me is to use the constructor:

Map<Key, Value> orgMap = new HashMap<Key, Value>();
Map<Key, Value> copyMap;
copyMap= new HashMap<Key, Value>(map);

Keep it simple.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!