Home > Software engineering >  Count Occurrences of words with Case sensitives
Count Occurrences of words with Case sensitives

Time:01-13

How can we find the occurrences of words in an array of Strings with Case sensitive

e.g. [AA, Bb, Aa, aa, BB] ===> {AA=3, Bb=2}

[AAa,aaa,BBB,bbb,BbB,AaA,AAc]  ===> {AAa=3, BBB=3 , AAc=1}

The count should be against the first appearance of the word

ConcurrentHashMap<String,Integer> hm = new ConcurrentHashMap<>(); String[] s1 = {"AA", "Bb", "Aa", "aa", "BB"};

    for (String s:s1) {
        if (hm.size()==0)
            hm.put(s,1);
        else {
            Set<String> keySet = hm.keySet();
            for (String s2 : keySet) {
                if (s2.equalsIgnoreCase(s)) {
                    Integer val = hm.get(s2);
                    hm.put(s2,   val);
                    break;
                } else {
                    hm.put(s, 1);
                }
            }
        }
    }

    System.out.println(hm);

CodePudding user response:

TreeMap allows you to provide a custom key comparator. One such comparator is String.CASE_INSENSITIVE_ORDER.

final TreeMap<String, Integer> treeMap
        = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
final String[] s1 = {"AA", "Bb", "Aa", "aa", "BB"};

for (final String s : s1) {
    treeMap.merge(s, 1, Integer::sum);
}

System.out.println(treeMap);

Output:

{AA=3, Bb=2}

I know, boring. Where's the fun in that? :)

  • Related