🟢 How to Count Characters in a String using Java 8 Stream API Input type: String = "Welocometoprogrammming" Output Type : Map<Character, Long> ✅ Code Example import java.util.*; import java.util.stream.*; import java.util.function.Function; public class Main { public static void main(String[] args) { String str = "Welocometoprogrammming"; Map<Character, Long> chCount = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println(chCount); } } Output: {a=1, c=1, e=2, g=2, i=1, l=1, m=4, n=1, o=4, p=1, r=2, t=1, W=1} 🧠 Let’s Understand the Approach 🔹 Do we need a filter? ➡️ No, because we want to count all characters. 🔹 Do we need transformation? ➡️ No logical transformation, only type conversion. 🔹 Why chars()? ➡️ chars() converts the String into an IntStream of character ASCII values. 🔹 Why mapToObj()? ➡️ Because char is a primitive type, and Stream operations work on objects. So we convert each int to Character. 🔹 Why collect()? ➡️ Because the final result needs to be stored in Map<Character, Long>. ❓ What is Function.identity()? Function.identity() is a static method from java.util.function.Function. ✔️ It returns the same input as output ✔️ It is a replacement for this lambda: c -> c ✔️ Used when key and value are the same object Example: Collectors.groupingBy(Function.identity(), Collectors.counting()) Means: 👉 Group characters by themselves and count occurrences. #Java #Java8 #StreamAPI #Coding #InterviewPreparation #JavaStream #Multithreading
Java 8 Stream API: Counting Characters in a String
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
-
🚀 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
To view or add a comment, sign in
-
-
🔥 Tricky Java String Concatenation Test public class StringConcate { public static void main(String[] args) { String s1 = "Welcome"; String s2 = new String("To"); String s3 = new String(); //Case 1 s1.concat("Java"); System.out.println(s1); //case 2 s3=s1.concat("Java"); System.out.println(s3); //case3 s3=s1+s2; System.out.println(s3); } } Guess the output ? 👏 Let understand We have created 🧠 Memory Creation 🔹 s1 → String Constant Pool (SCP) → "Welcome" 🔹 s2 → Heap memory (created using new) 🔹 s3 → Empty String object in Heap 📌 Important: 👉 All String objects in Java are immutable 🔹 Case 1 s1.concat("Java"); System.out.println(s1); concat() creates a new String → "WelcomeJava" Result is not assigned s1 still points to "Welcome" ✅ Output :Welcome 🔹 Case 2 s3 = s1.concat("Java"); System.out.println(s3); New String "WelcomeJava" is created This time, it is assigned to s3 s1 remains unchanged ✅ Output : WelcomeJava 🔹 Case 3 s3 = s1 + s2; System.out.println(s3); + operator is used Internally converted to: new StringBuilder() .append(s1) .append(s2) .toString(); A new String object is created Assigned to s3 ✅ Output : WelcomeTo #Java #String #JavaInterview #CoreJava #StringImmutability #Developer #CodingInterview
To view or add a comment, sign in
-
-
#day16 #FunctionalInterfaces A functional interface in Java is an interface that has only one abstract method, making it suitable for use with lambda expressions and method references (introduced in Java 8). a. Use @FunctionalInterface to ensure only one abstract method (annotation is optional). b. Enable clean, concise code using lambdas and method references. #@FunctionalInterface Annotation @FunctionalInterface annotation ensures that an interface cannot have more than one abstract method. If multiple abstract methods are present, the compiler throws an “Unexpected @FunctionalInterface annotation” error. #Types of Functional Interfaces in Java Java 8 introduced four main functional interface types under the package java.util.function. These are widely used in Stream API, collections and lambda-based operations. 1. Consumer -: Consumer interface of the functional interface is the one that accepts only one argument. It is used for performing an action, such as printing or logging. There are also functional variants of the Consumer DoubleConsumer, IntConsumer and LongConsumer. 2. Predicate :- Predicate interface represents a boolean-valued function of one argument. It is commonly used for filtering operations in streams. There are also functional variants of the Predicate IntPredicate, DoublePredicate and LongPredicate. 3. Function:- The function interface takes one argument and returns a result. It is commonly used for transforming data. Several variations exist: Bi-Function: Takes two arguments and returns a result. Unary Operator: Input and output are of the same type. Binary Operator: Like BiFunction but with same input/output type. 4. Supplier:- Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output. The different extensions of the Supplier functional interface hold many other suppliers functions like BooleanSupplier, DoubleSupplier, LongSupplier and IntSupplier. #leetcode #gfg #interviewbit #Consistency #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Java Array A data structure that stores multiple values of the same data type in a single variable. Arrays Class A utility class in Java that provides methods to perform operations on arrays such as sorting and searching. String A class used to represent a sequence of characters in Java; String objects are immutable. String Methods Predefined methods used to manipulate and retrieve information from String objects. StringBuffer and StringBuilder Classes used to create mutable strings; StringBuffer is thread-safe, while StringBuilder is faster but not thread-safe. Immutable and Mutable Immutable objects cannot be changed after creation, while mutable objects can be modified. Exception Handling A mechanism to handle runtime errors and maintain the normal flow of program execution. Shallow Copy and Deep Copy Shallow copy copies object references, while deep copy creates a new independent object. File Handling A process of creating, reading, writing, and deleting files in Java. Multithreading A feature that allows multiple threads to execute concurrently within a program. Synchronization A mechanism used to control access to shared resources in a multithreaded environment. Interthread Communication A technique that allows threads to communicate with each other during execution. Deadlock A situation where two or more threads wait indefinitely for each other’s resources. Daemon Thread A background thread that runs to support user threads and terminates when they finish. Inner Class A class defined inside another class to logically group related classes. Object Class The root superclass of all Java classes from which every class implicitly inherits. pdf Link :- https://lnkd.in/gXEWSAJ2 #Java #CoreJava #JavaDeveloper #JavaInterview #ProgrammingBasics #SoftwareDevelopment #LearnJava #StudentDeveloper #TechLearning
To view or add a comment, sign in
-
-
"DSA in Java: Previous Smaller Element using Stack" Post Content: Ever wondered how to find the previous smaller element for each item in an array efficiently? Here's a clean Java solution using Stack (no extra libraries needed besides java.util.Stack). import java.util.Stack; public class PreviousSmallerElement { public static void main(String[] args) { int[] arr = {4, 5, 2, 10, 8}; int[] result = new int[arr.length]; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < arr.length; i++) { // Remove elements bigger or equal to current while (!stack.isEmpty() && stack.peek() >= arr[i]) { stack.pop(); } // Decide the answer if (stack.isEmpty()) { result[i] = -1; } else { result[i] = stack.peek(); } // Push current element for future comparison stack.push(arr[i]); } // Print result for (int x : result) { System.out.print(x + " "); } } } ✅ Output: -1 4 -1 2 2 Explanation: For each element, we check the previous smaller element on the left. If none exists, we return -1. Stack makes this process O(n) instead of using nested loops. #Java #DSA #DataStructures #Stack #Algorithms #Coding #Programming #InterviewPrep #CompetitiveProgramming #TechLearning #SoftwareEngineering #LeetCode
To view or add a comment, sign in
-
📘 Core Java – Day 5 Topic: Loops (for loop & simple pattern) Today, I learned about the concept of Loops in Core Java. Loops are used to execute a block of code repeatedly, which helps in reducing code redundancy and improving efficiency. In Java, the main types of loops are: 1. for loop 2. while loop 3. do-while loop 4. for-each loop 👉 I started by learning the for loop. 🔹 Syntax of for loop: for(initialization; condition; increment/decrement) { // statements } 🔹 Working of for loop: Initialization – initializes the loop variable (executed only once) Condition – checked before every iteration Execution – loop body runs if the condition is true Increment/Decrement – updates the loop variable Loop continues until the condition becomes false ⭐ Example: Simple Star Pattern using for loop for(int i = 1; i <= 5; i++) { for(int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🔹 Key Points: ✔ for loop is used when the number of iterations is known ✔ It keeps code structured and readable ✔ Nested for loops are commonly used in pattern programs 🚀 Building strong fundamentals in Core Java, one concept at a time. #CoreJava #JavaLoops #ForLoop #JavaProgramming #LearningJourney #Day5
To view or add a comment, sign in
-
🚀 Java 8 Streams – A Small Problem That Tests Big Concepts Today I revisited a classic interview question that seems simple but hides some heavy duty concepts: 👉 Find the last repeating character in a string using Java 8 Streams. Example: Input: "programming" Output: g (The repeated chars are 'r', 'g', 'm'. 'g' is the last one to appear in the original sequence.) Here is an elegant way to solve it: Java String input = "programming"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // Key: Maintains insertion order Collectors.counting() // Value: Frequency count )) .entrySet() .stream() .filter(e -> e.getValue() > 1) .reduce((first, second) -> second) // The "Last" logic .map(Map.Entry::getKey); result.ifPresent(System.out::println); ✨ Why this is a great test of fundamentals: It’s not just about the syntax it’s about what’s happening under the hood: It’s easy to write code that works it’s harder to write code that is both expressive and efficient. I’m curious how would you tackle this 😄? 1️⃣ Stick to the modern Streams approach? 2️⃣ Go back to a traditional for loop for potential performance gains? 3️⃣ Use a different collection entirely? #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #CleanCode #InterviewQuestion
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
-
-
🚀 Can the main method be Overloaded in Java? Short answer: YES ✅ But with an important catch 👇 🔹 What does overloading mean? Method overloading means having multiple methods with the same name but different parameters. 🔹 Can main() be overloaded? Yes, the main method can be overloaded just like any other method in Java. 👉 However, JVM will always call only this signature: public static void main(String[] args) Other overloaded main methods won’t be executed automatically. 🔹 Example: Overloading main() public class MainExample { public static void main(String[] args) { System.out.println("Original main method"); main(10); main("Hello"); } public static void main(int a) { System.out.println("Overloaded main with int: " + a); } public static void main(String s) { System.out.println("Overloaded main with String: " + s); } } Original main method Overloaded main with int: 10 Overloaded main with String: Hello 🔹 Key Points to Remember 💡 ✔️ main()can be overloaded ✔️ JVM always starts execution from public static void main(String[] args) ✔️ Overloaded main() methods must be called explicitly ❌ Overloading does not change program entry point 📌 Interview Tip: If someone asks “Can we overload the main method in Java?” Say: 👉 Yes, but JVM will only call the standard main method signature. #Java #JavaInterview #CoreJava #Programming #CodingTips #SoftwareEngineering
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
CountCharacters: String str = "Welocometoprogrammming"; Map<Character, Long> CountCharacters=str.chars().mapToObj(c->(char)c).collect(Collectors.groupingBy(Function.identity(),Collectors.counting())); System.out.print("CountCharacters "+CountCharacters);