Java 8 Stream API: Find First Non-Repeating Character with LinkedHashMap

🚀 Java 8 Stream API – Find First Non-Repeating Character 🔹 Problem Statement Find the first non-repeating character using Stream API Input: String Output: Character 📌 Example Input → "swiss" Output → w ✅ Java 8 Solution import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class FirstNonRepeatingCharacter { public static void main(String[] args) { String str = "swiss"; LinkedHashMap<Character, Long> collect = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, Collectors.counting() )); Character result = collect.entrySet() .stream() .filter(e -> e.getValue() == 1) .map(Map.Entry::getKey) .findFirst() .orElse(null); System.out.println(result); // w } } 🔍 Let’s Understand the Approach 1️⃣ Input is String, output is Character So first, we convert the string into characters. 2️⃣ chars() ➡ Converts String into IntStream of character ASCII values. 3️⃣ mapToObj(c -> (char) c) ➡ Converts primitive int to Character object. 4️⃣ groupingBy + counting() ➡ Counts occurrences of each character. 5️⃣ Why LinkedHashMap and not HashMap? 👉 LinkedHashMap maintains insertion order 👉 Required to find the first non-repeating character. 6️⃣ Filter entries where count == 1 ➡ These are non-repeating characters. 7️⃣ findFirst() ➡ Returns the first non-repeating character based on original order. #Java #Java8 #StreamAPI #CodingInterview #BackendDevelopment #SpringBoot #ProblemSolving #LinkedHashMap

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories