Java Program to Find Duplicate Characters in a String - 5 Ways

In this section, we will show you five different ways to find duplicate characters in a given String in Java.

1. Using For loop 

2. Using Enhanced for loop

3. Using Java 9 chars() method

4. Using Java 8 Streams

5. Using Google Guava MultiSet

Example 1. Using For loop

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Main {

public static void main(String[] args) {

String str = "hellojava";

Map<Character,Integer> occurrences = new HashMap<>();
Set<Character> characterSet = new HashSet<>();

for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (occurrences.containsKey(c)) {
int count = occurrences.get(c);
occurrences.put(c, ++count);
characterSet.add(c);
} else {
occurrences.put(c, 1);
}
}
System.out.println(characterSet);
}
}

Here we iterate through string chars. Check whether map contains specific key. If map contains specific key get the value(count) and put the key and value(++count) inside HashMap. HashMap don't allow for duplicate keys. The second value should just replace the previous value. 

A Set cannot contain duplicate elements. So we are adding characters whose value count is greater than one to Set.


Example 2. Using Enhanced for loop

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

public class Main {

public static void main(String[] args) {

String str = "hellojava";

Map<Character, Integer> occurrences = new LinkedHashMap<>();

for (Character ch : str.toCharArray()) {
Integer count = occurrences.get(ch);
occurrences.put(ch, count == null ? 1 : ++count);
}

for (Map.Entry<Character,Integer> entry : occurrences.entrySet())
if(entry.getValue()>1){
System.out.println(entry.getKey());
}
}
}

Here we iterate through string array. Get the count (value). Then put it to the Map, if count(value) is 'null' we put value as 1, if count(value) is 'not null' put value as count+1. The second value should just replace the previous value. It will not allow duplicate keys.

Finally iterate the Map using forEach and print the elements whose value is greater than one.


Example 3. Using Java 9 chars() method

import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

String str = "hellojava";

str.chars().mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(c -> c, Collectors.counting())).
forEach((k,v)-> {
if(v>1) {
System.out.println(k); }
});
}
}

chars() returns an IntStream that consists of the code point values of the characters in the given string. This method was integrated to the String class in Java 9. 

mapToObj() is an intermediate operation, it is a method of IntStream interface is used to return an object-valued stream.

Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.

Collectors counting() method is used to count the number of elements passed in the stream as the parameter.

Finally we are iterating over map using forEach and print the character whose count is greater than one.


Example 4. Using Java 8 Streams

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

String str = "hellojava";

Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(c -> c , Collectors.counting()))
.forEach((k,v)->{
if(v>1){
System.out.println(k);
}
});

}
}

stream() method accepts a mandatory parameter array which is the array of whose elements are to be converted into a sequential stream and returns a Sequential Stream from the array passed as the parameter.

split() method is used to split the String.

Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.

Collectors counting() method is used to count the number of elements passed in the stream as the parameter.

Finally we are iterating over map using forEach and print the character whose count is greater than one.


Example 5. Using Google Guava MultiSet

First add Google Guava to your project: https://mvnrepository.com/artifact/com.google.guava/guava
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

public class Main {

public static void main(String[] args) {

String str = "hellojava";
char[] characters = str.toCharArray();

Multiset<Character> frequencies = HashMultiset.create();
for (Character character : characters) {
frequencies.add(character);
}

for (Character character : frequencies.elementSet()) {
if(frequencies.count(character)>1){
System.out.println(character);
}
}
}
}

A Multiset is an collection that is kindred to Set, but it may have duplicate elements. The duplicate elements are fortified by maintaining a count of the total number of times an element appears in the collection.

More Interesting topics,


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete