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
Find Longest String in Java 8 with Reduce
More Relevant Posts
-
🚀 Day 20 – Optional in Java (Handling Nulls the Right Way) One common issue in Java: NullPointerException Today I explored how "Optional" helps handle this more safely. --- 👉 Traditional way: String name = user.getName(); if (name != null) { System.out.println(name); } --- 👉 Using "Optional": Optional<String> name = Optional.ofNullable(user.getName()); name.ifPresent(System.out::println); --- 💡 Why use "Optional"? ✔ Avoids direct null checks everywhere ✔ Makes code more readable and expressive ✔ Encourages better handling of missing values --- 💡 Useful methods: - "orElse()" → default value - "orElseGet()" → lazy default - "orElseThrow()" → throw exception if empty --- ⚠️ Insight: "Optional" is great, but should be used wisely—not for every variable, mainly for return types. --- 💡 Takeaway: Handling nulls properly = more robust and maintainable code #Java #BackendDevelopment #Java8 #Optional #CleanCode #LearningInPublic
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
-
🚀 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
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
-
Java Evolution: From Java 8 to Java 25 Most developers still use Java, but very few truly understand how much it has evolved. Here’s a breakdown of how Java transformed from a verbose language into a modern, developer-friendly powerhouse. Java 8 (2014) – The Game Changer - Lambda Expressions → Functional programming - Stream API → Cleaner data processing - Optional → Null safety - Default methods in interfaces This is where modern Java began. Java 9–11 – Modularity & Stability - Module System - JShell - HTTP Client API (modern replacement) - Local-variable type inference (var) Java became more modular and lightweight. Java 12–17 – Developer Productivity Boost - Switch expressions (cleaner control flow) - Text Blocks (multi-line strings) - Records (boilerplate killer) - Pattern Matching (instanceof improvements) - Sealed Classes (controlled inheritance) Less boilerplate, more clarity. Java 18–21 – Performance + Modern Features - Virtual Threads - Structured Concurrency - Record Patterns - Pattern Matching for switch (finalized) - Generational ZGC Java becomes cloud-native and concurrency-friendly. Java 22–25 – The Future is Here - String Templates (safe string interpolation) - Scoped Values (better than ThreadLocal) - Unnamed Classes & Instance Main Methods - Enhanced Pattern Matching (more expressive) - Continued JVM performance and GC improvements Java is now faster, cleaner, and more expressive than ever.
To view or add a comment, sign in
-
-
🚀 Java Series – Day 28 📌 Reflection API in Java (How Spring Uses It) 🔹 What is it? The **Reflection API** allows Java programs to **inspect and manipulate classes, methods, fields, and annotations at runtime**. It allows operations like **creating objects dynamically, invoking methods, and reading annotations** without hardcoding them. 🔹 Why do we use it? Reflection helps in: ✔ Dependency Injection – automatically injects beans ✔ Annotation Processing – reads `@Autowired`, `@Service`, `@Repository` ✔ Proxy Creation – supports AOP and transactional features For example: In Spring, it can detect a class annotated with `@Service`, create an instance, and inject it wherever required without manual wiring. 🔹 Example: `import java.lang.reflect.*; @Service public class DemoService { public void greet() { System.out.println("Hello from DemoService"); } } public class Main { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("DemoService"); // load class dynamically Object obj = clazz.getDeclaredConstructor().newInstance(); // create instance Method method = clazz.getMethod("greet"); // get method method.invoke(obj); // invoke method dynamically } }` 🔹 Output: `Hello from DemoService` 💡 Key Takeaway: Reflection makes Spring **dynamic, flexible, and powerful**, enabling features like DI, AOP, and annotation-based configuration without manual coding. What do you think about this? 👇 #Java #ReflectionAPI #SpringBoot #JavaDeveloper #BackendDevelopment #TechLearning #CodingTips
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
-
-
💡Functional Interfaces in Java — The Feature That Changed Everything When Java 8 introduced functional interfaces, it quietly transformed the way we write code. At first, it may look like “just another interface rule” — but in reality, it unlocked modern Java programming. 🔹 What is a Functional Interface? A functional interface is simply an interface with exactly one abstract method. @FunctionalInterface interface Calculator { int operate(int a, int b); } That’s it. But this “small restriction” is what makes lambda expressions possible. 🔹 Why Do We Need Functional Interfaces? Before Java 8, passing behavior meant writing verbose code: Runnable r = new Runnable() { @Override public void run() { System.out.println("Running..."); } }; Now, with functional interfaces: Runnable r = () -> System.out.println("Running..."); 👉 Cleaner 👉 More readable 👉 Less boilerplate 🔹 The Real Power: Passing Behavior Functional interfaces allow us to pass logic like data. list.stream() .filter(x -> x % 2 == 0) .map(x -> x * 2) .forEach(System.out::println); Instead of telling Java how to do something, we describe what to do. This is called declarative programming — and it’s a game changer. 🔹 Common Built-in Functional Interfaces Java provides powerful utilities in "java.util.function": - Predicate<T> → condition checker - Function<T, R> → transformation - Consumer<T> → performs action - Supplier<T> → provides value 🔹 Why Only One Abstract Method? Because lambda expressions need a clear target. If multiple abstract methods existed, the compiler wouldn’t know which one the lambda refers to. 👉 One method = One behavior contract 🔹 Real-World Impact Functional interfaces are everywhere: ✔ Stream API ✔ Multithreading ("Runnable", "Callable") ✔ Event handling ✔ Spring Boot (filters, callbacks, transactions) ✔ Strategy pattern 🔹 Key Takeaway Functional interfaces turned Java from: ➡️ Object-oriented only into ➡️ Object-oriented + Functional programming hybrid 🔁 If this helped you understand Java better, consider sharing it with your network. #Java #FunctionalProgramming #Java8 #SoftwareDevelopment #Backend #SpringBoot #Coding
To view or add a comment, sign in
-
-
Most Java developers use int and Integer without thinking twice. But these two are not the same thing, and not knowing the difference can cause real bugs in your code. Primitive types like string, int, double, and boolean are simple and fast. They store values directly in memory and cannot be null. Wrapper classes like Integer, Double, and Boolean are full objects. They can be null, they work inside collections like lists and maps, and they come with useful built-in methods. The four key differences every Java developer should know are nullability, collection support, utility methods, and performance. Primitives win on speed and memory. Wrapper classes win on flexibility. Java also does something called autoboxing and unboxing. Autoboxing is when Java automatically converts a primitive into its wrapper class. Unboxing is the opposite, converting a wrapper class back into a primitive. This sounds helpful, and most of the time it is. But when a wrapper class is null and Java tries to unbox it, your program will crash with a NullPointerException. This is one of the most common and confusing bugs that Java beginners and even experienced developers run into. The golden rule is simple. Use primitives by default. Switch to wrapper classes only when you need null support, collections, or utility methods. I wrote a full breakdown covering all of this in detail, with examples. https://lnkd.in/gnX6ZEMw #Java #JavaDeveloper #Programming #SoftwareDevelopment #Backend #CodingTips #CleanCode #100DaysOfCode
To view or add a comment, sign in
-
-
Most Java developers write code. Very few write good Java code🔥 Here are 10 Java tips every developer should know 👇 1. Prefer interfaces over implementation → Code to "List" not "ArrayList" 2. Use "StringBuilder" for string manipulation → Avoid creating unnecessary objects 3. Always override "equals()" and "hashCode()" together → Especially when using collections 4. Use "Optional" wisely → Avoid "NullPointerException", but don’t overuse it 5. Follow immutability where possible → Makes your code safer and thread-friendly 6. Use Streams, but don’t abuse them → Readability > fancy one-liners 7. Close resources properly → Use try-with-resources 8. Avoid hardcoding values → Use constants or config files 9. Understand JVM basics → Memory, Garbage Collection = performance impact 10. Write meaningful logs → Debugging becomes 10x easier Clean code isn't about writing more. It’s about writing smarter. Which one do you already follow? 👇 #Java #JavaDeveloper #SoftwareEngineering #BackendDevelopment #SpringBoot #CleanCode #Programming #Developers #TechTips #CodingLife
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