Stone
Stone

Reputation: 79

Frequency of a number in a different approach

I have a string= "helloworld" I am trying to find the frequency of each character in a string and I'm using TreeMap to store because it store in ascending order. I know the approach of using
Map= new TreeMap
but it will sort the alphabets in e=1,h=1, l=2, o=2 like this. So i used
TreeMap map= new Treemap
so that it can sort like this 1=h, 1=w, 1=r, 1=d, 2= l so that I can get the out put like this
lohewrd
i.e The max occuring letter will be placed first then the second lowest.
Since I have tried putting the values in tree map but it not giving the desired result.

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package forinterview;

import java.util.Map;
import java.util.TreeMap;

/**
 *
 * @author Amal
 */
public class RemoveDuplicate {
    public static void main(String[] args){
        String s= "geeksforgeeks";

        Map<Integer,Character> map= new TreeMap<Integer,Character>();

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

            char c= s.charAt(i);
            Integer value= sendKey(map,c);
            //System.out.println(value);
            if(value != null){
                map.put((value)+1, c);
            }else{
                map.put(1, c);
            }
        }

        System.out.println(map);
    }

    private static Integer sendKey(Map<Integer, Character> map, char c) {
        for(Map.Entry<Integer, Character> entry:map.entrySet()){
            if(c == (entry.getValue())){
                return entry.getKey();
            }
        }
        return null;
    }
}

Here I have used another method to get the keys because when Im using
int value =map.get(ch[i) inside loop so that I can increse the value with value+1 it's showing error.

Upvotes: 0

Views: 90

Answers (2)

sulabh singh
sulabh singh

Reputation: 44

Your current approach will give incorrect output because you are replacing character on the basis of count of occurrence. Let us take example: String s="Fighter Jet" Character 'e' and 't' occurred twice in our string. According to your code character 'e' will get replaced by 't'.

**Please try below code for reference to find character occurrence **

public void countAlphabets(String s){


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

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

          char c= s.charAt(i);
// Counting occurrence of alphabets
        if(map.containsKey(c)){
            map.put(c, map.get(c)+1);
        }
        else{
            map.put(c, 1);
        }
      }

     //Sorting Hashmap by values
  Set<Entry<String, Integer>> set = map.entrySet();
  List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
  Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
  {
      public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
      {
          return (o2.getValue()).compareTo( o1.getValue() );
      }
  } );
  for(Map.Entry<String, Integer> entry:list){
      System.out.println(entry.getKey()+" ==== "+entry.getValue());
  }
  }

Method countAlphabets take one argument i.e String and will print Character with their occurrence count in ascending order.

Upvotes: 2

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

You could use Collectors.groupingBy and filter them into a stream:

String s = "helloworld";
String[] array = s.split("(?!^)");

Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
    .entrySet().stream()
    .sorted(Comparator.comparing(a -> a.getValue()))
    .forEach(key -> System.out.print(key.getKey()));

Upvotes: 2

Related Questions