This program finds the first non-repeated character in a String using Java Stream functions. It groups characters by their occurrence count using Collectors.groupingBy() with a LinkedHashMap (to preserve insertion order), then filters for the first character whose count is exactly 1.
Code Example:
import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
public class FirstNonRepeated {
public static void main(String args[]) {
String input = "Java articles are Awesome";
Character result = input.chars()
.mapToObj(s -> Character.toLowerCase(Character.valueOf((char) s)))
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
}Output:
j