• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Test Cases
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Programs » Write A Program to Print Duplicate Character & Count-In Java?

Write A Program to Print Duplicate Character & Count-In Java?

Last Updated on: November 4, 2018 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Write A Program to Print Duplicate Character & Count-In Java?

Write A Program to Print Duplicate Character & Count-In Java?

package com.java.collection.hashset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Details 
{
   public void countDupChars(String str)
   {	 
      //Create a HashMap 
      Map<Character, Integer> map = new HashMap<Character, Integer>(); 
      //Convert the String to char array
      char[] chars = str.toCharArray();
      /* logic: char are inserted as keys and their count
       * as values. If map contains the char already then
       * increase the value by 1
       */
      for(Character ch:chars)
      {
         if(map.containsKey(ch))
         {
            map.put(ch, map.get(ch)+1);
         }
         else
         {
            map.put(ch, 1);
         }
      }
      //Obtaining set of keys
      Set<Character> keys = map.keySet();
      /* Display count of chars if it is
       * greater than 1. All duplicate chars would be 
       * having value greater than 1.
       */
      for(Character ch:keys)
      {
         if(map.get(ch) > 1)
         {
            System.out.println("Char "+ch+" "+map.get(ch));
         }
      }
   }
   public static void main(String a[]){
      Details obj = new Details();
      System.out.println("SoftwareTestingBlog");
      System.out.println("-------------------------");
      obj.countDupChars("mm");

   }
}

Reference: Article

    Filed Under: Java Programs

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2022 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers