Find Duplicate Characters In a String Java

In this blog post, we will learn a java program to find the duplicate characters in a string. To find the duplicate character from a string, we can count the occurrence of each character in the string. If any character has a count greater than 1, then it is a duplicate character.

This question is very popular in Junior level Java programming interviews, where you need to write code. The difficulty level for this question is the same as questions about prime numbers or the Fibonacci series, which are also popular among junior programmers. Every programmer should know how to solve these types of questions.

Post Type:Java Programs For Beginners
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Duplicate Characters In a String Java

We will try to Find Duplicate Characters In a String Java in two ways:

  • Brute Force Method (Without using collection)
  • Hash map method (Using collection)

Find Duplicate Characters In a String Java: Brute Force Method

package com.softwaretestingo.interviewprograms;
public class FindDuplicateCharactersEx3 
{
	public static void main(String[] args) 
	{
		// input string
		String string = "softwaretestingo";
		System. out.println("The string is: " + string);

		// covert the string to the char array
		char s[] = string.toCharArray();
		int i = 0;
		// Traverse the string from left to right
		System.out.print("The duplicate characters in the string are: ");
		for (i = 0; i < s.length; i++)
		{
			// For each character count the frequency
			int count = 1;
			// s[i] == '0' means we have already visited this character so no need to count its frequency again.
			if (s[i] == '0')
				continue;
			int j = i + 1;
			for (j = i + 1; j < s.length; j++) 
			{
				// If a match found increase the count by 1
				if (s[i] == s[j]) {
					count++;
					s[j] = '0';
				}
			}

			// If count is more than one then print it
			if (count > 1) 
			{
				System.out.print(s[i] + " ");
			}
		}
	}
}

Find Duplicate Characters in a String Java HashMap Method

I find this exercise beneficial for beginners as it allows them to get comfortable with the Map data structure. This data structure is useful as it stores mappings in key-value form.

If you’re looking to get into enterprise Java programming, it’s a good idea to brush up on your knowledge of Map and Hash table data structures. These are heavily used in enterprise Java applications, so having a strong understanding of them will give you a leg up when applying for jobs

We use a HashMap and Set to find out which characters are duplicated in a given string. We convert the string into a character array, then create a HashMap with Characters as keys and the number of times they occur as values. Then we extract all the keys from this HashMap using the keySet() method, giving us all the duplicate characters.

package com.softwaretestingo.interviewprograms;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FindDuplicateCharactersEx1 
{
	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[] args) 
	{
		FindDuplicateCharactersEx1 obj = new FindDuplicateCharactersEx1();
		obj.countDupChars("softwaretestingo");

	}
}

Count Duplicate Characters in a String Java

You can also follow the below programs to find out Find Duplicate Characters In a String Java. Here To find out the duplicate character, we have used the java collection concept. If you want to check then you can follow the java collections framework link.

package com.softwaretestingo.interviewprograms;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FindDuplicateCharactersEx2 
{
	public static void printDuplicateCharacters(String str)
	{
		if(str == null)
		{
			System.out.println("NULL String");
			return;
		}
		if(str.isEmpty())
		{
			System.out.println("Empty String");
			return;
		}
		if(str.length()==1)
		{
			System.out.println("Single Char String");
			return;
		}
		char words[] = str.toCharArray();// java
		Map<Character,Integer> charMap = new HashMap<Character,Integer>();
		for(Character ch: words)
		{
			if(charMap.containsKey(ch))
			{
				charMap.put(ch,charMap.get(ch)+1);
			}
			else
			{
				charMap.put(ch,1);
			}
		} 
		System.out.println("Entered Substring: "+str);
		// print the map:
		Set<Map.Entry<Character, Integer >> entrySet = charMap.entrySet();
		System.out.println("Duplicate Character"+":"+"Count");
		for(Map.Entry<Character, Integer>entry : entrySet)
		{
			if(entry.getValue()>1)
			{
				System.out.println(entry.getKey()+"                    :"+entry.getValue());
			}
		}
	}
	public static void main(String[] args) 
	{
		printDuplicateCharacters(null);
		printDuplicateCharacters("");
		printDuplicateCharacters("A");
		printDuplicateCharacters("Softwaretestimgo");
	}
}

Output:

NULL String
Empty String
Single Char String
Entered Substring: Softwaretestimgo
Duplicate Character:Count
t                    :3
e                    :2
o                    :2

Remove Duplicate Characters in a String

If you’re looking to remove duplicate or repeated characters from a String in Java, this is the page for you! We’ll walk through how to solve this problem step by step. This problem is similar to removing duplicate elements from an array – if you know how to solve that problem, you should be able to solve this one as well.

We can remove the duplicate character in the following ways:

  • Using StringBuilder
  • Using HashSet
  • Using Java Streams

Remove Duplicate Characters in a String using StringBuilder

This problem can be solved by using the StringBuilder. To do this, take each character from the original string and add it to the string builder using the append() method. Then, when adding the next character use indexOf() method on the string builder to check if that char is already present in the string builder. If it is already present then it will not be added again to the string builder.

package com.softwaretestingo.interviewprograms;
public class RemoveDuplicateCharactersEx1 
{
	public static void main(String[] args) 
	{
		String orignalString = "softwaretestingo";
		StringBuilder builder = new StringBuilder();

		for (int i = 0; i < orignalString.length(); i++) 
		{
			if (builder.indexOf(String.valueOf(orignalString.charAt(i))) == -1) 
			{
				builder.append(orignalString.charAt(i));
			}
		}

		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + builder.toString());
	}
}

Output:

Original String : softwaretestingo
After removing the duplicates : softwareing

Remove Duplicate Characters in a String using HashSet

Next, we use the collection API HashSet class and each char is added to it. The add() method returns false if the given char is already present in the HashSet. The process is repeated until the last character of the string. This way, in the end, StringBuilder will only contain distinct values.

package com.softwaretestingo.interviewprograms;
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicateCharactersEx2 
{
	public static void main(String[] args) 
	{
		String orignalString = "softwaretestingo";
		StringBuilder builder = new StringBuilder();

		Set<Character> set = new HashSet<>();
		char[] chars = orignalString.toCharArray();

		for (char ch : chars) 
		{
			if (set.add(ch)) 
			{
				builder.append(ch);
			}
		}
		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + builder.toString());
	}
}

Output:

Original String : softwaretestingo
After removing the duplicates : softwareing

Remove Duplicate Characters in a String using Java Stream

At last, we will see how to remove the duplicate character using the Java Stream.

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
import java.util.stream.Collectors;
public class RemoveDuplicateCharactersEx3 
{
	public static void main(String[] args) 
	{
		String orignalString = "Java";

		String output = Arrays.asList(orignalString.split(""))
				.stream()
				.distinct()
				.collect(Collectors.joining());
		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + output);
	}
}

Output:

Original String : Java
After removing the duplicates : Jav

Conclusion:

In this detailed blog post of java programs questions for the interview, we have discussed in detail Find Duplicate Characters In a String Java and remove the duplicate characters from a string.

Thanks for taking the time to read this coding interview question! If you found it helpful, please share it with your friends and colleagues. If you have any questions or feedback, please don’t hesitate to leave a comment below.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment