Java Program to Find the First Repeated Character in a String

In this section, we will show you three different ways to find first repeated character in a given String in Java.

1. Using For loop and Map

2. Using Java 9 chars() method

3. Using Java 8 Streams

Example 1. Using For loop and Map

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

public class Main {

public static void main(String[] args) {

String str ="javaworld";

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

for (Character character : str.toCharArray()) {
if (map.containsKey(character)) {
map.put(character, map.get(character) + 1);
} else {
map.put(character, 1);
}

if (map.get(character) > 1) {
System.out.println(character);
break;
}
}
}
}

Here the logic is simple,

toCharArray() convert String to char Array.

Iterate over Character Array and check whether map contains specific key. If map contains specific key get the value(count) and put the key and value(+1) inside LinkedHashMap. 

LinkedHashMap don't allow for duplicate keys. The second value should just replace the previous value. The main advantage of utilizing LinkedHashMap is that it maintains and tracks the order of insertion.

Finally, print first element(value>1) from LinkedHashMap and break the loop. That's it! 

Console Output: 

a


Example 2. Using Java 9 chars() method

import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

String str ="javahello";

Optional<Character> firstRepeatedCharacter =
str.chars().mapToObj(i -> (char) i)
.collect(Collectors.
groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.counting()))
.entrySet().stream().filter(m -> m.getValue() > 1)
.map(m -> m.getKey())
.findFirst();

if(firstRepeatedCharacter.isPresent()) {
System.out.println(firstRepeatedCharacter.get());
};

}
}

chars() returns IntStream of char values. This method was integrated to the String class in Java 9. 

mapToObj() is an intermediate operation, here it returns Stream of Character.

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.

Here, the main advantage of utilizing LinkedHashMap is that it maintains and tracks the order of insertion.

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

entrySet() returns a set view of all the entries from the LinkedHashMap.

Using filter() method we filter the elements whose value is greater than one.

Using map() method we are converting Stream of Entry<Character,Long> to Stream of Character.

Finally, we are printing the first element.

Console Output: 

a


Example 3. Using Java 8 Streams

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

String str ="javahello";

Optional<Character> firstRepeatedCharacter =
Arrays.stream(str.split("")).map(o -> o.charAt(0))
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()))
.entrySet().stream().filter(m -> m.getValue() > 1)
.map(m -> m.getKey())
.findFirst();

if(firstRepeatedCharacter.isPresent()) {
System.out.println(firstRepeatedCharacter.get());
};
}
}

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.

Using map() method we are converting Stream<String> to Stream<Character>.

Rest of the things are explained in example 2. 

Console Output: 

a

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

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