Java Streams: First Non-Repeating Character Solution

🚀 Java Streams Practice - First Non-Repeating Character Ever come across this classic question? 👉 "Find the first non-repeating character in a string" Here’s a clean and efficient way to solve it using Java Streams 👇 String str = "swiss"; 💡 Approach Explained 1️⃣ Convert String → Stream of Characters i. str.chars() gives an IntStream .mapToObj(c -> (char) c) converts it into a Stream<Character> 2️⃣ Count Frequency (Preserving Order) i. Collectors.groupingBy(...) groups characters ii. Function.identity() -> key is the character itself iii. Collectors.counting() -> counts occurrences iv. LinkedHashMap::new -> preserves insertion order (important!) 👉 Why LinkedHashMap? Because we need the first non-repeating character in the original order. 3️⃣ Filter First Non-Repeating Character i. entrySet().stream() -> iterate over map entries ii. .filter(e -> e.getValue() == 1) -> only unique characters iii. .map(Map.Entry::getKey) -> extract character iv. .findFirst() -> get first match 🧠 Pro Tip If you use HashMap instead of LinkedHashMap, you might get the wrong answer because order is not guaranteed. 💬 Have you solved this problem differently? Drop your approach in the comments! 💻 I’ve added my Java solution in the comments below. Please let me know if there are any other approaches I could try. #Java #Java8 #JavaStreams #CodingInterview #DSA #FunctionalProgramming #Developers #BackendDevelopment

  • text

public class StreamPractice { 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 character = collect.entrySet().stream().filter(e -> e.getValue() == 1).map(Map.Entry::getKey) .findFirst().orElse(null); System.out.println("First non-repeating character: " + character); } }

Like
Reply

The trap here is that `(char)c` will break on surrogate pairs.

See more comments

To view or add a comment, sign in

Explore content categories