Find the first non-repeated character in Java 8 (Streams and Lambda)



Write a Java 8 program (using Stream API and Lambda expressions) that returns the first non-repeated character from a given string.

Java 8 program to find the first non-repeated character

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

public final class Strings {

    public static char firstNonRepeatedCharacterV1(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return Character.MIN_VALUE;
        }

        Map<Integer, Long> chs = str.chars()
                .mapToObj(cp -> cp)
                .collect(Collectors.groupingBy(Function.identity(),
                        LinkedHashMap::new, Collectors.counting()));

        return (char) (int) chs.entrySet().stream()
                .filter(e -> e.getValue() == 1L)
                .findFirst()
                .map(Map.Entry::getKey)
                .orElse(Integer.valueOf(Character.MIN_VALUE));
    }

    public static char firstNonRepeatedCharacterV2(String str) {
        Map<Integer, Long> chs = str.codePoints()
                .mapToObj(cp -> cp)
                .collect(Collectors.groupingBy(Function.identity(),
                        LinkedHashMap::new, Collectors.counting()));

        int cp = chs.entrySet().stream()
                .filter(e -> e.getValue() == 1L)
                .findFirst()
                .map(Map.Entry::getKey)
                .orElse(Integer.valueOf(Character.MIN_VALUE));

        return (char) cp;
    }
}

Test

public class Main {

	private static final String TEXT = " Java is my fav programming language. I love Java coding";

    public static void main(String[] args) {
    	
    	System.out.println("Java 8, functional-style solution:");
        char firstcharV1 = Strings.firstNonRepeatedCharacterV1(TEXT);

        System.out.println("Found character: " + firstcharV1);
        
        System.out.println("Java 8 stream and lambda, functional-style solution:");

        char firstcharV3 = Strings.firstNonRepeatedCharacterV2(TEXT);

        System.out.println("Found character: " + firstcharV3);
    }
}

Output:

Java 8, functional-style solution:
Found character: s
Java 8 stream and lambda, functional-style solution:
Found character: s

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments