Find duplicate characters in a String in Java

You have been given a string and you need to find occurrences of a characters. For ex. if given String is "Hello" then count for 'l' character should be 2.

Lets see coding part now.


package com.infybuzz.string;

import java.util.HashMap;
import java.util.Map;

public class FindDuplicateChars {

 public static void main(String[] args) {
  
  String str = "infybuzz";
  
  Map<Character, Long> charCounts = new HashMap<Character, Long>();
  
  char[] charArray = str.toCharArray();
  
  for (Character ch : charArray) {
   
   Long count = charCounts.get(ch);
   
   if (count == null) {
    count = 1L;
   } else {
    count++;
   }
   
   charCounts.put(ch, count);
  }
  
  System.out.println(charCounts.get('z'));
  
 }

}

Output


2

Remove duplicate characters from a String in Java
How many ways to create Object in Java ?