🚀 Day 19 – map() vs flatMap() in Java Streams While working with Streams, I came across a subtle but important difference: "map()" vs "flatMap()". --- 👉 map() Transforms each element individually List<String> names = Arrays.asList("java", "spring"); names.stream() .map(String::toUpperCase) .forEach(System.out::println); ✔ Output: JAVA, SPRING --- 👉 flatMap() Flattens nested structures List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4) ); list.stream() .flatMap(Collection::stream) .forEach(System.out::println); ✔ Output: 1, 2, 3, 4 --- 💡 Key insight: - "map()" → 1-to-1 transformation - "flatMap()" → 1-to-many (and then flatten) --- ⚠️ Real-world use: "flatMap()" is very useful when dealing with: - Nested collections - API responses - Complex data transformations --- 💡 Takeaway: Understanding when to use "flatMap()" can make your stream operations much cleaner and more powerful. #Java #BackendDevelopment #Java8 #Streams #LearningInPublic
map() vs flatMap() in Java Streams: Transform and Flatten
More Relevant Posts
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream #Java #Streams #Backend #SpringBoot #Developers #CleanCode
To view or add a comment, sign in
-
-
#Post4 In the previous post, we understood how request mapping works using @GetMapping and others. Now the next question is 👇 How does Spring Boot handle data sent from the client? That’s where @RequestBody comes in 🔥 When a client sends JSON data → it needs to be converted into a Java object. Example request (JSON): { "name": "User", "age": 25 } Controller: @PostMapping("/user") public User addUser(@RequestBody User user) { return user; } 👉 Spring automatically converts JSON → Java object This is done using a library called Jackson (internally) 💡 Why is this useful? • No manual parsing needed • Clean and readable code Key takeaway: @RequestBody makes it easy to handle request data in APIs 🚀 In the next post, we will understand @PathVariable and @RequestParam 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Streams #Backend #CodingInterview #SpringBoot #Developers #InterviewPrep #CleanCode
To view or add a comment, sign in
-
-
Day 23/100 — Functional Interfaces 🔧 Master these 4, and you unlock the real power of Java 8+ ⚡ ☕ Predicate → test() → boolean Think: Bouncer → allows or rejects isEven.test(4) // true 🍳 Function<T, R> → apply() → transforms data Think: Chef → ingredient → dish length.apply("Java") // 4 🖨️ Consumer → accept() → no return Think: Printer → takes input, returns nothing 🎰 Supplier → get() → no input Think: Vending machine → gives output getRandom.get() 💡 Why it matters: These are the backbone of Streams, Lambdas, and clean functional-style coding in Java. 🔗 Combine Predicates like logic gates: isEven.and(isPositive) // AND isEven.or(isPositive) // OR isEven.negate() // NOT (→ isOdd) 🎯 Challenge: Filter numbers that are BOTH even AND > 10 👇 Predicate isEven = n -> n % 2 == 0; Predicate greaterThan10 = n -> n > 10; numbers.stream() .filter(isEven.and(greaterThan10)) .forEach(System.out::println); Simple concepts. Massive impact. 🚀 #Java #Java8 #FunctionalProgramming #Predicate #Coding #100DaysOfCode #100DaysOfJava #Developers
To view or add a comment, sign in
-
-
𝐖𝐡𝐲 𝐢𝐬 𝐦𝐲 𝐂𝐮𝐬𝐭𝐨𝐦 𝐀𝐧𝐧𝐨𝐭𝐚𝐭𝐢𝐨𝐧 𝐫𝐞𝐭𝐮𝐫𝐧𝐢𝐧𝐠 𝐧𝐮𝐥𝐥? 🤯 Every Java developer eventually tries to build a custom validation or logging engine, only to get stuck when method.getAnnotation() returns null. The secret lies in the @Retention meta-annotation. If you don't understand these three levels, your reflection-based engine will never work: 1️⃣ SOURCE (e.g., @Override, @SuppressWarnings) Where? Only in your .java files. Why? It’s for the compiler. Once the code is compiled to .class, these annotations are GONE. You cannot find them at runtime. 2️⃣ CLASS (The default!) Where? Stored in the .class file. Why? Used by bytecode analysis tools (like SonarLint or AspectJ). But here's the kicker: the JVM ignores them at runtime. If you try to read them via Reflection — you get null. 3️⃣ RUNTIME (e.g., @Service, @Transactional) Where? Stored in the bytecode AND loaded into memory by the JVM. Why? This is the "Magic Zone." Only these can be accessed by your code while the app is running. In my latest deep dive, I built a custom Geometry Engine using Reflection. I showed exactly how to use @Retention(RUNTIME) to create a declarative validator that replaces messy if-else checks. If you’re still confused about why your custom metadata isn't "visible," this breakdown is for you. 👇 Link to the full build and source code in the first comment! #Java #Backend #SoftwareArchitecture #ReflectionAPI #CleanCode #ProgrammingTips
To view or add a comment, sign in
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
Understanding the Magic Under the Hood: How the JVM Works ☕️⚙️ Ever wondered how your Java code actually runs on any device, regardless of the operating system? The secret sauce is the Java Virtual Machine (JVM). The journey from a .java file to a running application is a fascinating multi-stage process. Here is a high-level breakdown of the lifecycle: 1. The Build Phase 🛠️ It all starts with your Java Source File. When you run the compiler (javac), it doesn't create machine code. Instead, it produces Bytecode—stored in .class files. This is the "Write Once, Run Anywhere" magic! 2. Loading & Linking 🔗 Before execution, the JVM's Class Loader Subsystem takes over: • Loading: Pulls in class files from various sources. • Linking: Verifies the code for security, prepares memory for variables, and resolves symbolic references. • Initialization: Executes static initializers and assigns values to static variables. 3. Runtime Data Areas (Memory) 🧠 The JVM manages memory by splitting it into specific zones: • Shared Areas: The Heap (where objects live) and the Method Area are shared across all threads. • Thread-Specific: Each thread gets its own Stack, PC Register, and Native Method Stack for isolated execution. 4. The Execution Engine ⚡ This is the powerhouse. It uses two main tools: • Interpreter: Quickly reads and executes bytecode instructions. • JIT (Just-In-Time) Compiler: Identifies "hot methods" that run frequently and compiles them directly into native machine code for massive performance gains. The Bottom Line: The JVM isn't just an interpreter; it’s a sophisticated engine that optimizes your code in real-time, manages your memory via Garbage Collection (GC), and ensures platform independence. Understanding these internals makes us better developers, helping us write more efficient code and debug complex performance issues. #Java #JVM #SoftwareEngineering #Programming #BackendDevelopment #TechExplainers #JavaVirtualMachine #CodingLife
To view or add a comment, sign in
-
-
Java Bug: Overriding equals() Without hashCode() Can Break Your Entire Application This is one of the most common — and dangerous — mistakes I still encounter in Java backend codebases. Seen recently during a Spring Boot audit: The developer implemented equals() correctly… but forgot hashCode(). 👉 The result? Silent, unpredictable bugs in production. ❌ Vulnerable Code Example public class User { private String email; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return email.equals(user.email); } } 💥 Why This Breaks Things Collections like HashSet, HashMap, and ConcurrentHashMap rely on hashCode(), not just equals(). If two objects are equal but have different hash codes: HashSet may allow duplicates HashMap may fail to retrieve values Cache layers become inconsistent Bugs appear randomly and are hard to reproduce 🧠 Real-World Example Set<User> users = new HashSet<>(); users.add(new User("test@mail.com")); users.add(new User("test@mail.com")); System.out.println(users.size()); // Can return 2 🤯 ✅ The Fix (Always Apply This Rule) 👉 If you override equals(), you MUST override hashCode() @Override public int hashCode() { return Objects.hash(email); } 🔥 What I’ve Seen in Production Duplicate users in databases Broken caching layers Inconsistent business logic Intermittent bugs that waste hours of debugging 🛡️ Best Practice Never rely on equals() alone. Always respect the equals/hashCode contract defined in Java. 🚨 Quick Question How many of your domain classes correctly implement both equals() and hashCode()? #Java #JavaDev #SpringBoot #Backend #SoftwareEngineering #CleanCode #Programming #Debugging #TechDebt #Performance
To view or add a comment, sign in
-
-
🚀 Java Records — Clean, Concise, and Immutable Data Models Tired of writing boilerplate code for simple data carriers in Java? That’s exactly where Java Records shine ✨ 👉 Introduced in Java 14 (finalized in Java 16), records provide a compact way to model immutable data. 🔹 What is a Record? A record is a special type of class designed to hold data — no unnecessary getters, setters, equals(), hashCode(), or toString() needed. 🔹 Example: java public record User(String name, int age) {} That’s it. Java automatically generates: ✔️ Constructor ✔️ Getters (name(), age()) ✔️ equals() & hashCode() ✔️ toString() 🔹 Why use Records? ✅ Less boilerplate → more readability ✅ Immutable by default → safer code ✅ Perfect for DTOs, API responses, and data transfer ✅ Encourages clean architecture 🔹 Custom logic? You still can: java public record User(String name, int age) { public String nameInUpperCase() { return name.toUpperCase(); } } 🔹 Important points: ⚠️ Fields are final ⚠️ Cannot extend other classes (but can implement interfaces) ⚠️ Best suited for data carriers, not business-heavy objects 💡 When to use? - Microservices DTOs - API request/response models - Immutable configurations 👉 Records are a step toward more expressive and maintainable Java code. Are you using records in your projects yet? 🤔 #Java #Java17 #BackendDevelopment #CleanCode #SoftwareEngineering #FullStackDev
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