🚀 Day 5 of Java 8 Series 👉 Question: Find the frequency of each word in a given sentence using Java 8 Streams. import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class WordFrequency { public static void main(String[] args) { String sentence = "java is great and java is powerful"; Map<String, Long> frequencyMap = Arrays.stream(sentence.split("\\s+")) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println(frequencyMap); } } Output: {java=2, powerful=1, and=1, is=2, great=1} 🧠 Key Concepts Explained 👉 1. Arrays.stream() Converts an array into a Stream, which allows us to perform functional operations like filtering, grouping, and counting. In this example, after splitting the sentence into words, we use it to start the stream pipeline. 👉 2. split("\\s+") (Regex) \\s → matches any whitespace (space, tab, newline) + → matches one or more occurrences 💡 This ensures that even if there are multiple spaces between words, the sentence is split correctly into individual words. 👉 3. Collectors.groupingBy() This is used to group elements based on a key. Here, we group words by their value (Function.identity()) So all same words come under one group Example: java → [java, java] 👉 4. Collectors.counting() Used along with groupingBy() to count the number of elements in each group. Instead of storing a list of words, it directly gives the frequency #Java #Java8 #Streams #Coding #Developers #Learning
Java 8 Streams: Word Frequency Counter
More Relevant Posts
-
Java Puzzle for Today What will be the output of this program? String a = "Java"; String b = "Java"; String c = new String("Java"); System.out.println(a == b); System.out.println(a == c); System.out.println(a.equals(c)); Take a moment and guess before scrolling. Most beginners think the output will be: true true true But the actual output is: true false true Why does this happen? Because Java stores string literals in a special memory area called the String Pool. So when we write: String a = "Java"; String b = "Java"; Both variables point to the same object in the String Pool. But when we write: String c = new String("Java"); Java creates a new object in heap memory, even if the value is the same. That’s why: - "a == b" → true (same object) - "a == c" → false (different objects) - "a.equals(c)" → true (same value) Lesson: Use "equals()" to compare values, not "==". Small Java details like this can save you from real bugs in production. #Java #Programming #JavaPuzzle #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 Day 6 of Java Series — Count Vowels Using Streams Ever wondered how to count vowels in a string using Java 8 in a clean and functional way? Here’s a simple yet powerful approach using Streams 👇 import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class CountOfVowels { public static void main(String[] args) { String name = "Microservices"; List<String> vowels = Arrays.asList("a", "e", "i", "o", "u"); Map<String, Long> map = Arrays.stream(name.split("")) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); List<Map.Entry<String, Long>> finalMap = map.entrySet().stream() .filter(entry -> vowels.contains(entry.getKey())) .toList(); System.out.println(finalMap); } } 🔍 How it works: 1️⃣ name.split("") → Converts string into individual characters 2️⃣ groupingBy(Function.identity(), counting()) → Counts frequency of each character 3️⃣ Filter step → Keeps only vowels 4️⃣ Final result → List of vowels with their count 👉 Output: [e=2, i=2, o=1] #Java #Java8 #Streams #Coding #Developers #Learning
To view or add a comment, sign in
-
Hello Connections, Post 17 — Java Fundamentals A-Z This one confuses every Java developer at least once. 😱 Can you spot the bug? 👇 public static void addTen(int number) { number = number + 10; } public static void main(String[] args) { int x = 5; addTen(x); System.out.println(x); // 💀 5 or 15? } Most developers say 15. The answer is 5. 😱 Java ALWAYS passes by value — never by reference! Here’s what actually happens 👇 // ✅ Understanding the fix public static int addTen(int number) { number = number + 10; return number; // ✅ Return the new value! } public static void main(String[] args) { int x = 5; x = addTen(x); // ✅ Reassign the result! System.out.println(x); // ✅ 15! } But wait — what about objects? public static void addName(List<String> names) { names.add("Mubasheer"); // ✅ This WORKS! } public static void main(String[] args) { List<String> list = new ArrayList<>(); addName(list); System.out.println(list); // [Mubasheer] ✅ } 🤯 Java passes the REFERENCE by value! You can modify the object — but not reassign it! Post 17 Summary: 🔴 Unlearned → Java passes objects by reference 🟢 Relearned → Java ALWAYS passes by value — even for objects! 🤯 Biggest surprise → This exact confusion caused a method to silently lose transaction data! Have you ever been caught by this? Drop a 📨 below! #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 Follow along for more! 👇
To view or add a comment, sign in
-
-
🚀 Java 8 changed everything — and this is one of the biggest reasons why. While deepening my understanding of Java internals, I spent time breaking down Anonymous Inner Classes, Functional Interfaces, and Lambda Expressions — three concepts that completely change how you write Java. At first, it feels like just syntax. But when you look closer, it’s really about how Java represents and handles behavior. 🔹 Anonymous Inner Class Allows us to declare and instantiate a class at the same time—without giving it a name. Useful when the implementation is needed only once. Greeting greeting = new Greeting() { public void greet(String name) { System.out.println("Welcome " + name); } }; ⚠️ Cons: -> Code is bulky -> Can only access effectively final variables -> Harder for the JVM to optimize 🔹 Functional Interface An interface with exactly one abstract method. Can still have multiple default and static methods. @FunctionalInterface public interface Greeting { void greet(String name); } 🔹 Lambda Expression (Java 8+) A more compact way to represent behavior — like an anonymous method. name -> System.out.println("Welcome " + name); 💡 What stood out to me: ⚙️ Anonymous Class → multiple lines ⚙️ Lambda Expression → one line Same logic, less noise — that’s where modern Java stands out.” #Java #LambdaExpressions #FunctionalInterface #BackendDevelopment #CleanCode #Java8 #SoftwareEngineering
To view or add a comment, sign in
-
Same result. Half the code. Most Java developers don’t use this 😱 Java Fundamentals Series | Part 21 Can you spot the improvement? 👇 List<String> names = Arrays.asList( "Alice", "Bob", "Charlie" ); // ❌ Verbose Lambda names.forEach(name -> System.out.println(name)); // ✅ Method Reference names.forEach(System.out::println); Cleaner. More readable. More professional. 💪 4 Types of Method References 👇 // 1. Static method Function<Integer, Integer> abs = Math::abs; // 2. Instance method of object Function<String, String> upper = String::toUpperCase; // 3. Instance method of instance String prefix = "DBS: "; Function<String, String> addPrefix = prefix::concat; // 4. Constructor reference Function<String, StringBuilder> builder = StringBuilder::new; Real-world example 👇 // ❌ Lambda transactions.stream() .map(t -> t.getAmount()) .forEach(a -> System.out.println(a)); // ✅ Method Reference transactions.stream() .map(Transaction::getAmount) .forEach(System.out::println); Summary: 🔴 Writing lambdas everywhere 🟢 Use method references when method already exists 🤯 Cleaner code = fewer lines + better readability ⸻ 👉 Posting more real-world fixes like this. Have you used method references? Drop a :: below 👇 #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2
To view or add a comment, sign in
-
-
🚀 Understanding the Diamond Problem in Java (with Example) The Diamond Problem happens in languages that support multiple inheritance—when a class inherits the same method from two different parent classes, causing ambiguity about which one to use. 👉 Good news: Java avoids this completely for classes. 🔒 Why Java Avoids It - Java allows single inheritance for classes → no ambiguity. - Uses interfaces for multiple inheritance. - Before Java 8 → interfaces had no implementation → no conflict. - After Java 8 → "default methods" can create a similar issue, but Java forces you to resolve it. --- 💥 Problem Scenario (Java 8+ Interfaces) interface A { default void show() { System.out.println("A's show"); } } interface B { default void show() { System.out.println("B's show"); } } class C implements A, B { // Compilation Error: show() is ambiguous } 👉 Here, class "C" doesn't know whether to use "A"'s or "B"'s "show()" method. --- ✅ Solution: Override the Method class C implements A, B { @Override public void show() { A.super.show(); // or B.super.show(); } } ✔ You explicitly choose which implementation to use ✔ No confusion → no runtime bugs --- 🎯 Key Takeaways - Java design prevents ambiguity at the class level - Interfaces give flexibility but require explicit conflict resolution - Always override when multiple defaults clash --- 💡 If you think Java is "limited" because it doesn’t allow multiple inheritance… you're missing the point. It’s intentional design to avoid chaos, not a limitation. #Java #OOP #Programming #SoftwareEngineering #Java8 #CleanCode
To view or add a comment, sign in
-
-
Day 4 of Java Series 👉 Find the Longest String using Java 8 Streams (reduce) Java 8 introduced powerful Stream APIs, and one of the most underrated methods is reduce() — perfect for aggregating results. 💡 Problem: Find the longest string from a given list. 💻 Solution: import java.util.*; public class LongestStringUsingReduce { public static void main(String[] args) { List<String> list = Arrays.asList("Java", "Microservices", "Spring", "Docker"); String longest = list.stream() .reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2) .orElse(""); System.out.println("Longest String: " + longest); } } 🧠 How it works: stream() → Converts list into stream reduce() → Compares two elements at a time (word1, word2) -> ... → Keeps the longer string orElse("") → Handles empty list safely Finally returns the longest string ⚡ Time Complexity: O(n) — single pass through the list 🔥 Why use reduce()? Because it helps in converting a stream into a single result in a clean and functional way. Output: Microservices #Java #Java8 #Streams #Coding #Developers #Learning
To view or add a comment, sign in
-
Hello Connections, Post 20— Java Fundamentals A-Z This one compiles perfectly. But breaks everything at runtime. 😱 Can you spot the bug? 👇 @FunctionalInterface interface Calculator { int calculate(int a, int b); int multiply(int a, int b); // 💀 Won't compile! } The bug? A Functional Interface can have only ONE abstract method! Two abstract methods = not functional! 💀 Here’s the fix 👇 // ✅ One abstract method only! @FunctionalInterface interface Calculator { int calculate(int a, int b); // ✅ Only one! } // ✅ Use it with Lambda! Calculator add = (a, b) -> a + b; Calculator multiply = (a, b) -> a * b; Calculator subtract = (a, b) -> a - b; System.out.println(add.calculate(5, 3)); // 8 ✅ System.out.println(multiply.calculate(5, 3)); // 15 ✅ System.out.println(subtract.calculate(5, 3)); // 2 ✅ Java’s Built-in Functional Interfaces // Predicate — returns boolean Predicate<String> isEmpty = s -> s.isEmpty(); // Function — transforms input to output Function<String, Integer> length = s -> s.length(); // Consumer — takes input, returns nothing Consumer<String> print = s -> System.out.println(s); // Supplier — no input, returns value Supplier<String> greeting = () -> "Hello DBS!"; Post 20 Summary: 🔴 Unlearned → Functional Interface can have multiple methods 🟢 Relearned → Exactly ONE abstract method — that’s what makes it functional! 🤯 Biggest surprise → Built-in functional interfaces replaced 20+ custom interfaces in codebase! Which built-in functional interface do you use most? Drop below! 👇 #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 Follow along for more! 👇
To view or add a comment, sign in
-
-
📌 Optional in Java — Avoiding NullPointerException NullPointerException is one of the most common runtime issues in Java. Java 8 introduced Optional to handle null values more safely and explicitly. --- 1️⃣ What Is Optional? Optional is a container object that may or may not contain a value. Instead of returning null, we return Optional. Example: Optional<String> name = Optional.of("Mansi"); --- 2️⃣ Creating Optional • Optional.of(value) → value must NOT be null • Optional.ofNullable(value) → value can be null • Optional.empty() → represents no value --- 3️⃣ Common Methods 🔹 isPresent() Checks if value exists 🔹 get() Returns value (not recommended directly) --- 4️⃣ Better Alternatives 🔹 orElse() Returns default value String result = optional.orElse("Default"); 🔹 orElseGet() Lazy default value 🔹 orElseThrow() Throws exception if empty --- 5️⃣ Transforming Values 🔹 map() Optional<String> name = Optional.of("java"); Optional<Integer> length = name.map(String::length); --- 6️⃣ Why Use Optional? ✔ Avoids null checks everywhere ✔ Makes code more readable ✔ Forces handling of missing values ✔ Reduces NullPointerException --- 7️⃣ When NOT to Use Optional • As class fields • In method parameters • In serialization models --- 🧠 Key Takeaway Optional makes null handling explicit and safer, but should be used wisely. It is not a replacement for every null. #Java #Java8 #Optional #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
🔍 Understanding Arrays in Java (Memory & Indexing) Today I learned an important concept about arrays in Java: Given an array: int[] arr = {10, 20, 30, 40, 50}; We often think about how elements are stored in memory. In Java: ✔ Arrays are stored in memory (heap) ✔ Each element is accessed using an index ✔ JVM handles all memory internally So when we write: arr[0] → 10 arr[1] → 20 arr[2] → 30 arr[3] → 40 arr[4] → 50 👉 We are NOT accessing memory directly 👉 We are using index-based access Very-Important Point: 👉 Concept (Behind the scenes) we access elements using something like base + (bytes × index) in Java 💡 Let’s take an example: int[] arr = {10, 20, 30, 40, 50}; When we write: arr[2] 👉 We directly get 30 But what actually happens internally? 🤔 Behind the scenes (Conceptual): Address of arr[i] = base + (i × size) let's suppose base is 100 and we know about int takes 4 bytes in memory for every element :100,104,108,112,116 So internally: arr[2] → base + (2 × 4) Now base is : 100+8=108 now in 108 we get the our value : 30 Remember guys this is all happening behind the scenes 👉 You DON’T calculate it 👉 JVM DOES it for you 👉 But You Still need to know ✔ Instead, it provides safety and abstraction 🔥 Key Takeaway: “In Java, arrays are accessed using indexes, and memory management is handled by the JVM.” This concept is very useful for: ✅ Beginners in Java ✅ Understanding how arrays work internally ✅ Building strong programming fundamentals #Java #Programming #DSA #Coding #Learning #BackendDevelopment
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