Java Program to Find the First Non Repeating Character in a String

In this section, we will show you three different ways to find first non repeating 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 ="america";

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);
}
}
for(Map.Entry<Character,Integer> entry: map.entrySet())
{
if(entry.getValue()==1)
{
System.out.println(entry.getKey());
break;
}
}
}
}

toCharArray() returns character 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: 

m


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 ="america";

Optional<Character> firstNonRepeatedCharacter =
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(firstNonRepeatedCharacter.isPresent()) {
System.out.println(firstNonRepeatedCharacter.get());
};

}
}

chars() method returns an IntStream, it contains the integer code point values of the characters in the string object.

mapToObj() returns Stream of Character.

collect() method collects all objects from a stream object and stored in the LinkedHashMap.

groupingBy() method is used for grouping objects by some property and storing results in a Map instance.

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance.

This LinkedList maintains the insertion order.

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 equal to 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: 

m


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 ="america";

Optional<Character> firstNonRepeatedCharacter =
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(firstNonRepeatedCharacter.isPresent()) {
System.out.println(firstNonRepeatedCharacter.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: 

m

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