How to get distinct characters and their count in a string in java

What you will learn here about java

  • How to get distinct characters and their count in a string in java

How to get distinct characters and their count in a string in java is one of the common interview programming question. So here we will see How to get distinct characters and their count in a string in java

How to get distinct characters and their count in a string in java

import java.util.LinkedHashMap;
import java.util.Map;

public class Count 
{
	public static void main(String[] args)
	{
		String str="INFOSYS";
		Map <Character, String> map=new LinkedHashMap<Character, String>();
		
		for(int i=0;i<str.length();i++)
		{
		String temp=map.get(str.charAt(i));
			if(temp==null)
			{
				map.put(str.charAt(i), "1");
			}
			else
			{
				map.put(str.charAt(i), (Integer.parseInt(""+map.get(str.charAt(i)))+1)+"");
			}
		}
		
		System.err.println(map);
	}

}

OUTPUT

{I=1, N=1, F=1, O=1, S=2, Y=1}

You may also like...