Tuesday, December 27, 2016

Count no of String occurences in single pass

package com.prac;

import java.util.*;

public class CountStringOccurences 
{
public static void main(String[] args) {

String[] str = {"A","B","C","A","A","B","B","B","B","B","C","A","D","E","E","F","D","D"};

Map<String, Integer> hm = new HashMap<String, Integer>();

int cnt=1;

for(String ans : str)
{
if(hm.containsKey(ans))  //check if the key is already present
{
 cnt=hm.get(ans); // if present then fetch its count and increment it
 cnt++;
}
else
{
   cnt=1; //else set count to 1
}

     hm.put(ans, cnt);  // add the data in map
}


System.out.println("hm="+hm);
}
}


Output:
hm={D=3, E=2, F=1, A=4, B=6, C=2}

No comments:

Post a Comment

Home