frequency of character in a string using collection java code example

Example 1: find the frequency of characters in a string in java

+++METHOD WITH NONDUP+++
public static String FrequencyOfChars(String str) {

String nonDup = "";

for(int i=0; i < str.length(); i++)

if(!nonDup.contains(""+str.charAt(i)))

nonDup+= ""+str.charAt(i);

 String expectedResult = "";

for( int j=0;j < nonDup.length(); j++) {

int count = 0;

for(int i=0; i < str.length(); i++) {

if(str.charAt(i) == nonDup.charAt(j))

count++;
}

expectedResult +=nonDup.charAt(j)+"" + count;
}

return expectedResult;
}



+++METHOD WITH REPLACE METHOD+++
  
public  static  String  FrequencyOfChars(String str) {

String expectedResult = "";

for( int j=0; j < str.length(); j++) {

int count = 0;

for(int i=0; i < str.length(); i++) {

if(str.charAt(i) == str.charAt(j)) {

count++;
}
}

expectedResult +=str.charAt(j)+"" + count;

str = str.replace(""+str.charAt(j) ,  "" ); 
}

return expectedResult;

}

+++WITH LINKED HASH SET+++
  public  static  String  FrequencyOfChars(String str) {

String b=new LinkedHashSet<>(Arrays.asList(str.split(""))).toString();

  b = b.replace(", ","").replace("[","").replace("]","");

String result="";

for(int j=0; j<b.length();j++) {

int count=0;

for(int i=0; i<str.length(); i++){

if(str.substring(i, i+1).equals(""+str.charAt(j)))

count++;

}

result+=b.substring(j, j+1)+count;

}

return result;

}

++++LAST METHOD USING COLLECTIONS+++
  public static String frequency(String str) {

String nonDup="", result="";

for(int i=0; i < str.length(); i++)

if(! nonDup.contains(""+str.charAt(i)))

nonDup += ""+str.charAt(i);

 

for(int i=0; i < nonDup.length(); i++) {

int num = Collections.frequency( Arrays.asList(str.split("") ) ,    ""+nonDup.charAt( i ) );

result += ""+nonDup.charAt(i) + num;

}

 

return result;

}

Example 2: string frequency of characters in java

String str = "AAAABBCCDD"; // A4B2C2D2
        String result1 = "";
        String nonDup = "";

        for(int i=0; i < str.length(); i++)
            if(!nonDup.contains(""+str.charAt(i)))
                nonDup+= ""+str.charAt(i);

        for( int j=0;j < nonDup.length(); j++) {
            int count = 0;
            for(int i=0; i < str.length(); i++) {
                if(str.charAt(i) == nonDup.charAt(j))
                    count++;
            }
            result1 +=nonDup.charAt(j)+"" + count;
        }
        System.out.println(result1); // A4B2C2D2

Tags:

Java Example