In this tutorial, we will learn “Find the first non-repeating character in a string using Java 8?”. In order to do that, we are going to leverage the Stream API along with the Collectors.groupingBy collector.
Find the first non-repeated character in a string using Java 8
Find the first non-repeating character in a string using Java 8 Share on X
/**
* Using Java 8, Find the first non-repeating character in a string
* @author Deepak Verma
*
*/
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Find_first_non_repeating_character_in_string_Java8Stream {
public static void main(String[] args) {
String inputString = "Techndeck";
Optional<Character> ourcome = findFirstNonRepeatedCharacter(inputString);
ourcome.ifPresentOrElse(
character -> System.out.println("First Non-Repeated Character: " + character),
() -> System.out.println("There is No non-repeated character present in the string.")
);
}
public static Optional<Character> findFirstNonRepeatedCharacter(String inputStr) {
Map<Character, Long> charCountingMap = inputStr.chars()
.mapToObj(c -> (char) c)
.collect(
Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
)
);
return charCountingMap.entrySet().stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst();
}
}
Output:
First Non-Repeated Character: T
check if text or string present in a file using java 8
The code above defines a method findFirstNonRepeatedCharacter that takes a string as input and returns an Optional<Character> which represents the first non-repeated character.
Steps:
- Convert the input string to a stream of characters using
chars(). - Convert each character to a
Characterobject. - Use
Collectors.groupingByto group the characters by their counts in aLinkedHashMap. - Filter the entries to find characters with a count of 1.
- Map the entry set to characters.
- Use
findFirstto get the first non-repeated character.
skip method java 8 stream
Find the first non-repeating character in a string using Java 8 Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: