🚀 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
Java 8 Stream API: Find First Non-Repeating Character with LinkedHashMap
More Relevant Posts
-
🚀 Mastering String, StringBuffer & StringBuilder in Java Today I strengthened my understanding of one of the most important Core Java concepts: String handling and performance optimization. In Java, we commonly use String, StringBuffer, and StringBuilder to work with text, but choosing the right one makes a big difference in performance and memory efficiency. 🔹 String (Immutable) String objects cannot be changed once created. Any modification creates a new object in memory. ✔ Thread-safe ❌ Slower when modified frequently Example: String s = "Hello"; s = s + " World"; --- 🔹 StringBuffer (Mutable & Thread-safe) StringBuffer allows modification without creating new objects and is safe for multi-threaded environments. ✔ Mutable ✔ Thread-safe ❌ Slightly slower due to synchronization Example: StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); --- 🔹 StringBuilder (Mutable & Fastest) StringBuilder is similar to StringBuffer but not thread-safe, making it faster and ideal for single-threaded applications. ✔ Mutable ✔ Fastest performance ❌ Not thread-safe Example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); --- 📌 Key Interview Insight: • Use String → when data should not change • Use StringBuffer → multi-threaded environment • Use StringBuilder → single-threaded & high performance Understanding these differences helps write optimized, efficient, and scalable Java applications. #Java #CoreJava #Programming #SoftwareDevelopment #JavaDeveloper #LearningJourney #Coding
To view or add a comment, sign in
-
Day 19 – How to Access Static Members of a Class in Java? In Java, static members belong to the class, not to objects. That means 👇 You don’t need to create an object to access them. 🔹 Syntax ClassName.memberName; Simple. Direct. Object not required. 🔹 Example 1 – Accessing Static Variables & Methods class Demo1 { static int x = 100; static int y = 200; static void test() { System.out.println("running test() method"); } } class Demo2 { public static void main(String[] args) { System.out.println("x=" + Demo1.x); System.out.println("y=" + Demo1.y); Demo1.test(); } } 🔹 Output: x=100 y=200 running test() method Notice: We accessed everything using ClassName.memberName. 🔹 Example 2 – Modifying Static Variables class Demo3 { static int x = 100; static int y = 200; } class Mainclass1 { public static void main(String[] args) { System.out.println("x=" + Demo3.x); System.out.println("y=" + Demo3.y); System.out.println("Modifying x & y"); Demo3.x = 300; Demo3.y = 400; System.out.println("x=" + Demo3.x); System.out.println("y=" + Demo3.y); } } 🔹 Output: x=100 y=200 Modifying x & y x=300 y=400 ⚠ Important Concept 👉 static ≠ constant A static variable: Belongs to the class Is shared among all objects Can be modified If you want a constant, use: static final int VALUE = 100; #Java #CoreJava #JavaFullStack #LearningInPublic #Programming #BackendDevelopment
To view or add a comment, sign in
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
🔹 **Marker Interface in Java** A **Marker Interface** in Java is an empty interface (no methods) that is used to “mark” a class. The JVM or frameworks check for this marker and change behavior accordingly. 👉 In simple words: It tells Java – This class has special permission or behavior. No method body : Because they do not define the behaviour --- ✅ **How It Works** * Marker interface has **no methods** * Class implements marker interface * JVM / Framework checks using `instanceof` or reflection * Special processing is applied --- ✅ **Why It Is Used** ✔ To provide metadata to JVM or frameworks ✔ To enable special behavior without changing class structure ✔ Cleaner than adding flags or extra logic inside class --- ✅ **When To Use** ✔ When you want to tag classes for special processing ✔ When behavior should be decided externally (JVM / framework) ✔ When designing reusable framework-level features --- ✅ **Real-Time Examples** 📌 `Serializable` → Allows object to convert into byte stream 📌 `Cloneable` → Allows object cloning using `clone()` 📌 `RandomAccess` → Optimizes list performance (ArrayList vs LinkedList) --- ✅ **Simple Example** // Marker Interface interface Marker {} // Class implementing marker class TestClass implements Marker { void show() { System.out.println("Hello Marker"); } } // Checking Marker public class Main { public static void main(String[] args) { TestClass obj = new TestClass(); if(obj instanceof Marker) { System.out.println("Marker detected - Special behavior enabled"); } } } --- #Java #SpringBoot #Microservices #BackendDeveloper #Coding #SoftwareEngineering
To view or add a comment, sign in
-
💻 Java String Problem – Reverse Each Word in a Sentence. 🧠 Problem Statement: Input: "Prince Is Good Singer" Output: "ecnirP sI dooG regniS" 👉 Here, each word is reversed but the sentence order remains the same. 📌 Approach I followed: 1. Take the complete sentence as input. 2. Read the sentence character by character. 3. Create a word until a space is found. 4. When a space appears: a) reverse that word b) add it into the final result 5. Repeat the same process for all words. 6. At the end, reverse the last word and add to the result. 7. Print the final reversed-word sentence. 💡 Important Concept Used: 1. String traversal using loop 2. Character array conversion 3. Swapping logic to reverse a word 4. Building final output step by step 🧾 Java Implementation: public static String reverseWordInString(String str) { String word = ""; String desired_output = ""; for (char ch : str.toCharArray()) { if (ch != ' ') { word += ch; } else { desired_output += reverseString(word) + " "; word = ""; }} desired_output += reverseString(word); // reverse last word return desired_output; } public static String reverseString(String word) { char[] charArr = word.toCharArray(); int charArrLength = charArr.length; for (int i = 0; i < charArrLength / 2; i++) { char temp = charArr[i]; charArr[i] = charArr[charArrLength - 1 - i]; charArr[charArrLength - 1 - i] = temp; } return new String(charArr); } 🚀 Learning Outcome: 1. Improved Java string handling 2. Learned how to reverse words using logic 3. Strengthened problem-solving skills 4. Helpful for Java backend & interview preparation #java #javaPractice #CodingPractice #JavaDeveloper #BackendDeveloper #Programming #LearningJourney #InterviewPreparation
To view or add a comment, sign in
-
-
String vs StringBuilder vs StringBuffer in Java — Explained Simply If you work with Java, you encounter strings frequently. However, many developers may not clearly understand when to use "String," "StringBuilder," or "StringBuffer," and this misunderstanding can negatively impact performance. Let’s break it down logically. 1. String — Immutable A "String" object cannot be modified once created. String str = "Hello"; str.concat(" World"); System.out.println(str); Output: Hello Why? Because every modification creates a new object, leaving the original unchanged. Use when: - The value should not change - Safety and readability matter more than performance - Constants or fixed text 2. StringBuilder — Mutable & Fast "StringBuilder" allows modification without creating new objects. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb); Output: Hello World Changes happen in the same object, resulting in better performance. Use when: - Heavy string manipulation - Loops or dynamic text building - Single-threaded applications 3. StringBuffer — Mutable & Thread-Safe "StringBuffer" functions like "StringBuilder" but is synchronized. StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb); It is safe for multi-threaded environments but slightly slower due to synchronization. Use when: - Multiple threads access the same string - Data consistency is critical Quick Comparison Feature | String | StringBuilder | StringBuffer Mutability | ❌ Immutable | ✅ Mutable | ✅ Mutable Thread Safety | ✅ Yes | ❌ No | ✅ Yes Performance | Slow | Fastest | Medium Best For | Constant values | Single-thread operations | Multi-thread operations Simple Rule to Remember: - Fixed text → String - Performance needed → StringBuilder - Multi-thread safety → StringBuffer Understanding these differences can significantly enhance memory usage and application performance. #Java #Programming #SoftwareDevelopment #BackendDevelopment #JavaDeveloper #CodingConcepts
To view or add a comment, sign in
-
-
🚀 100 Days of Java Tips – Day 10 Topic: Modern Switch Expressions (Java 14+) If you’re still using the traditional switch statement with multiple break statements, it’s time to upgrade 😄 Java 14 introduced switch expressions to make your code cleaner, safer, and more readable. In older versions, switch was mainly used as a statement. That meant you had to manually assign values and remember to add break every time. Missing a break could silently introduce bugs. Example – Old Style Switch: String result; switch (day) { case "MONDAY": result = "Start of week"; break; case "FRIDAY": result = "Almost weekend"; break; default: result = "Mid week"; } Now let’s see the modern version. Example – New Switch Expression: String result = switch (day) { case "MONDAY" -> "Start of week"; case "FRIDAY" -> "Almost weekend"; default -> "Mid week"; }; What changed? • No need for break • Cleaner arrow syntax • Directly returns a value • Less chance of fall-through bugs You can also group cases: String type = switch (day) { case "SATURDAY", "SUNDAY" -> "Weekend"; default -> "Weekday"; }; Why this matters? Modern switch makes your intent clear. It reduces boilerplate code. It improves maintainability. Java is evolving to become more expressive and developer-friendly. If you are using Java 14 or above, start using switch expressions in new code. Write code that is not just working, but elegant. #Java #100DaysOfCode #JavaTips #Developers #ModernJava
To view or add a comment, sign in
-
-
🚀 Stop Writing Java Utility Classes the Old Way ✅ Use Functional Interfaces Instead Many Java projects still rely on large utility classes filled with static methods like this: public class StringUtils { public static String toUpper(String input) { return input == null ? null : input.toUpperCase(); } public static String trim(String input) { return input == null ? null : input.trim(); } } This works… but it’s rigid, harder to extend, and not very composable. 💡 A Better Approach: Functional Interfaces Using Java 8+ functional interfaces like Function , we can make our code more flexible: import java.util.function.Function; Function<String, String> toUpper = str -> str == null ? null : str.toUpperCase(); Function<String, String> trim = str -> str == null ? null : str.trim(); // Compose behaviors Function<String, String> trimAndUpper = trim.andThen(toUpper); System.out.println(trimAndUpper.apply(" hello world ")); 🚀 Why this is better? ✔ More reusable ✔ Easily composable (And then, compose) ✔ Cleaner testing ✔ Less boilerplate ✔ Encourages functional thinking Instead of creating another static utility method every time, you can pass behavior as a parameter. This is especially powerful in Spring Boot microservices, where flexibility and clean architecture matter. #Java #FunctionalProgramming #CleanCode #SpringBoot #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
📌 Why Java Doesn’t Support Multiple Inheritance (And How It Solves the Problem) One of the most common Java interview questions: Why doesn’t Java support multiple inheritance? Let’s understand the real reason. 🤯 The Problem – The Diamond Problem Imagine this: class A { void show() { System.out.println("From A"); } } class B extends A { } class C extends A { } // Now what if: class D extends B, C { } // ❌ Not allowed in Java Now think carefully. If both B and C inherit show() from A,and D inherits from both… 👉 Which show() should Java call? This ambiguity is called the Diamond Problem. Languages like C++ allow this and resolve it differently. Java decided to avoid this confusion entirely. 🚫 So Java Does NOT Allow: class D extends B, C No multiple inheritance with classes. ✅ But Java Still Allows Multiple Inheritance (Smartly) Through Interfaces. interface A { void show(); } interface B { void show(); } class D implements A, B { public void show() { System.out.println("Resolved in D"); } } Here: - No ambiguity - No inherited implementation conflict - Child class provides implementation - Clean. Explicit. Safe. 🔥 What About Default Methods? (Java 8+) - Java 8 introduced default methods in interfaces. - Now the ambiguity can reappear. - Java handles it like this: - If two interfaces provide the same default method, the implementing class must override it. - Explicit resolution. - No confusion. #Java #OOP #SoftwareEngineering #InterviewPreparation #JavaDeveloper
To view or add a comment, sign in
-
-
Most Java devs know you can't use multiple inheritance. But do you know all the types you CAN'T extend — even without the final keyword? 🤔 The rule is simple: a class can only extend ONE parent. But Java has several types that block inheritance through different mechanisms — not always with final. Here's the full picture: → final class: The obvious one. Compiler blocks extension directly. → enum: Implicitly extends java.lang.Enum. Since Java doesn't allow multiple inheritance, no room for your class. → record (Java 16+): Implicitly final. Compiler rejects any attempt to extend it. → Arrays (int[], String[], etc.): They extend Object — confirmed by the Java Language Specification. But the JVM creates them at runtime, not as regular classes. You cannot extend them. Period. → Private constructor: No final needed. Since every child class must call super(), a private constructor silently kills inheritance. ```java class Singleton { private Singleton() { } // blocks extension AND multiple instances public static Singleton getInstance() { ... } } class Child extends Singleton { } // ❌ Won't compile ``` This is why the Singleton pattern gets a free "sealed" behavior — not by design choice, but as a side effect of the private constructor. The key insight: final is just ONE of the ways Java prevents inheritance. The language has multiple mechanisms, some explicit, some implicit, some enforced by the JVM itself. Understanding WHY something can't be extended makes you a better architect — not just a better coder. 🎯 📊 Java Language Specification - Arrays (JLS §10): https://lnkd.in/eSyKYpip 📊 Java Language Specification - Types and Values (JLS §4): https://lnkd.in/e5EGb-ps 📊 Java Arrays and Inheritance — Medium (Santiago Barbieri, 2024): https://lnkd.in/e9vziKWt #Java #SoftwareEngineering #BackendDevelopment #ObjectOrientedProgramming #CleanCode #JavaDeveloper #TechLeadership #Microservices
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development