Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count Occurrences of words with Case sensitives

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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? 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading