⚡ Lambdas & Functional Interfaces in Java What are they? Lambda expressions = short way to write anonymous functions. Functional Interface = interface with only one abstract method. 💡 Why use them? 1. Cleaner & less boilerplate code 2. Improves readability 3. Core for Streams & modern Java APIs 4. Encourages functional-style programming 🧩 Example Without Lambda: Runnable r = new Runnable() { public void run() { System.out.println("Running..."); } }; With Lambda: Runnable r = () -> System.out.println("Running..."); 🎯 Custom Functional Interface @FunctionalInterface interface Calculator { int operate(int a, int b); } Calculator add = (a, b) -> a + b; System.out.println(add.operate(2, 3)); // 5 🔁 Common Built-in Functional Interfaces 1. Predicate<T> → boolean result 2. Function<T, R> → transform input → output 3. Consumer<T> → takes input, no return 4. Supplier<T> → returns value, no input ⚙️ Flow Input → Lambda → Functional Interface → Output 🧠 Rule of Thumb If your interface has one method, think → "Can I replace this with a lambda?" 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #SpringBoot #Backend #FunctionalProgramming #Coding
Java Lambdas and Functional Interfaces Explained
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 👉 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
-
-
⚡ map vs flatMap in Java (Stream API) Definition: map() → Transforms each element 1:1 flatMap() → Transforms and flattens nested structures 🤔 Why use? 1. map() - When output is a single value per input - Simple transformations 2. flatMap() - When each element produces multiple values (collections/streams) - Avoid nested structures like List<List<T>> 💻 Example List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6) ); // map() → creates nested structure List<Stream<Integer>> mapResult = list.stream() .map(inner -> inner.stream()) .collect(Collectors.toList()); // flatMap() → flattens into single stream List<Integer> flatMapResult = list.stream() .flatMap(inner -> inner.stream()) .collect(Collectors.toList()); 🔄 Flow map() List<List> → Stream<List> → Stream<Stream> flatMap() List<List> → Stream<List> → Stream 🧠 Rule of Thumb 👉 If your transformation returns a single value → use map() 👉 If it returns a collection/stream → use flatMap() 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Backend #Streams #Java8 #CodingInterview #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
🔥 Day 15: Functional Interfaces & Lambda Expressions (Java) One of the core concepts behind modern Java (introduced in Java 8) — clean, concise, and powerful 👇 🔹 1. Functional Interface 👉 Definition: An interface that contains exactly one abstract method. ✔ Can have multiple default/static methods ✔ Annotated with @FunctionalInterface (optional but recommended) Examples: ✔ Runnable ✔ Callable ✔ Comparator 🔹 2. Lambda Expression 👉 Definition: A short way to implement a functional interface without creating a class. 🧠 Think of it as: “function without name” 🔹 Traditional Way vs Lambda 👉 Without Lambda: Runnable r = new Runnable() { public void run() { System.out.println("Hello Java"); } }; 👉 With Lambda: Runnable r = () -> System.out.println("Hello Java"); 🔹 Syntax (parameters) -> expression Examples: (int a, int b) -> a + b x -> x * x () -> System.out.println("Hi") 🔹 Why Use Lambda? ✔ Less boilerplate code ✔ Improves readability ✔ Enables functional programming ✔ Works perfectly with Streams 🔹 Built-in Functional Interfaces ✔ Predicate<T> → returns boolean ✔ Function<T, R> → transforms data ✔ Consumer<T> → performs action ✔ Supplier<T> → provides data 🔹 When to Use? ✔ When interface has one abstract method ✔ With collections & streams ✔ For cleaner and shorter code 💡 Pro Tip: Use lambda expressions with Streams to write powerful one-line operations 🚀 📌 Final Thought: "Write less code, do more work — that’s the power of Lambda." #Java #Lambda #FunctionalProgramming #Java8 #Programming #JavaDeveloper #Coding #InterviewPrep #Day15
To view or add a comment, sign in
-
-
🧩 Optional in Java What is Optional? A wrapper to represent a value that may be absent, helps avoid null and makes intent clear. ✅ Why use it? 1. Prevents NullPointerException 2. Forces explicit handling of missing values 3. Cleaner and more readable APIs ⚖️ Correct vs Wrong Usage 1️⃣ Return Types ❌ User findUser(int id); // may return null ✅ Optional<User> findUser(int id); 2️⃣ Fields & Params ❌ Optional<String> name; // field void process(Optional<String>); // param 👉 Adds confusion + not intended use ✅ String name; void process(String data); 3️⃣ Accessing Value ❌ user.get(); // unsafe ✅ user.orElse(defaultUser); user.orElseThrow(); 4️⃣ Best Use (Chaining 💡) return Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCity) .orElse("Unknown"); 🧠 Rule of Thumb 👉 Use Optional only for return types 👉 Avoid in fields, DTOs, method params 👉 Prefer map/flatMap over null checks 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #SpringBoot #Backend #CleanCode #CodingTips #Developers #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Java String vs StringBuffer vs StringBuilder — Explained Simply Understanding how Java handles memory, mutability, and performance can completely change how you write efficient code. Here’s the quick breakdown 👇 🔒 String Immutable (once created, cannot change) Stored in String Constant Pool (SCP) Memory efficient but costly in loops 🔐 StringBuffer Mutable + Thread-safe Slower due to synchronization Safe for multi-threaded environments ⚡ StringBuilder Mutable + Fast Not thread-safe Best choice for performance-heavy operations 🧠 Real Insight (Important for Interviews): 👉 "java" literals share the same memory (SCP) 👉 new String("java") creates a separate object 👉 s = s + "dev" creates a NEW object every time 👉 StringBuilder.append() modifies the SAME object 🔥 Golden Rule: Constant data → String Multi-threading → StringBuffer Performance / loops → StringBuilder ⚠️ Common Mistake: Using String inside loops 👇 Leads to multiple object creation → memory + performance issues 💬 Let’s Discuss (Drop your answers): Why is String immutable in Java? What happens when you use + inside loops? StringBuilder vs StringBuffer — what do you use by default? Difference between == and .equals()? Can StringBuilder break in multi-threading? 👇 I’d love to hear your thoughts! #Java #JavaDeveloper #Programming #Coding #SoftwareEngineering #InterviewPreparation #TechLearning #BackendDevelopment #PerformanceOptimization #Developers #JavaTips #LearnToCode #CleanCode
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
-
-
Ever wondered why we need a "StringBuilder" in Java when we already have "String"? 🤔 At first glance, "String" seems perfectly fine for handling text. But the real difference shows up when we start modifying or concatenating strings multiple times. 👉 The key point: Strings in Java are immutable. This means every time you concatenate a string, a new object is created in memory. Example: String str = "Hello"; str = str + " World"; str = str + "!"; Behind the scenes, this creates multiple objects: - "Hello" - "Hello World" - "Hello World!" This repeated object creation increases memory usage and puts extra load on the Garbage Collector (GC). 🚨 In scenarios like loops or heavy string manipulation, this can significantly impact performance. So where does "StringBuilder" help? "StringBuilder" is mutable, meaning it modifies the same object instead of creating new ones. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); sb.append("!"); ✅ Only one object is used and updated internally ✅ Faster performance ✅ Less memory overhead ✅ Reduced GC pressure When should you use it? ✔ When performing frequent string modifications ✔ Inside loops ✔ When building dynamic strings (logs, queries, JSON, etc.) 💡 Quick takeaway: - Use "String" for simple, fixed text - Use "StringBuilder" for dynamic or repeated modifications 💥 Advanced Tip: StringBuilder Capacity vs Length Most developers know StringBuilder is faster—but here’s something interviewers love 👇 👉 length() = actual number of characters 👉 capacity() = total allocated memory By default, capacity starts at 16 and grows dynamically when needed: ➡️ New capacity = (old * 2) + 2 💡 Why it matters? Frequent resizing creates new internal arrays and copies data → impacts performance. ✅ Pro tip: When working with loops or large data, initialize capacity in advance: StringBuilder sb = new StringBuilder(1000); Understanding this small concept can make a big difference in writing efficient Java code 🚀 #Java #Programming #Performance #CodingTips #Developers
To view or add a comment, sign in
-
-
🚀Stream API in Java - Basics Every Developer Should Know When I started using Stream API, I realized how much cleaner and more readable Java code can become. 👉Stream API is used to process collections of data in a functional and declarative way. 💡What is a Stream? A stream is a sequence of elements that support operations like: ->filtering ->mapping ->sorting ->reducing 💠Basic Example List<String> list = Arrays.asList("Java", "Python", "Javascript", "C++"); list.stream().filter(lang-> lang.startsWith("J")) .forEach(System.out : : println); 👉 outputs :Java, Javascript 💠Common Stream Operations ☑️filter() -> selects elements ☑️map() -> transforms data ☑️sorted() -> sorts elements ☑️forEach() -> iterates over elements ☑️collect() -> converts stream back to collection 💠Basic Stream Pipeline A typical stream works in 3 steps: 1. Source -> collection 2. Intermediate Operations -> filter, map 3. Terminal operation -> forEach, collect ⚡Why Stream API? . Reduces boilerplate code . Improves readability . Encourages functional programming . Makes data processing easier ⚠️Important Points to remember . Streams don't store data, they process it . Streams are consumed once . Operations are lazy (executed only when needed) And Lastly streams API may seem confusing at first, but with practice it becomes a go-to tool for working with collections. #Java #StreamAPI #JavaDeveloper #Programming #SoftwareEngineering #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Day 12 Today’s Java practice was about solving the Leader Element problem. Instead of using nested loops, I used a single traversal from right to left, which made the solution clean and efficient. A leader element is one that is greater than all the elements to its right. Example: Input: {16,17,5,3,4,2} Leaders: 17, 5, 4, 2 🧠 Approach I used: ->Start traversing from the rightmost element ->Keep track of the maximum element seen so far ->If the current element is greater than the maximum, it becomes a leader ->This is an efficient approach with O(n) time complexity and no extra space. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int a [] ={16,17,5,3,4,2}; int length=a.length; int maxRight=a[length-1]; System.out.print("Leader elements are :"+maxRight+" "); for(int i=a[length-2];i>=0;i--) { if(a[i]>maxRight) { maxRight=a[i]; System.out.print(maxRight+" "); } } } } Output:Leader elements are :2 4 5 17 #AutomationTestEngineer #Selenium #Java #DeveloperJourney #Arrays
To view or add a comment, sign in
-
-
🚀 Day 25 – Collections Tuning: Writing High-Performance Java Code Java Collections are powerful — but default usage ≠ optimal performance. As an architect, understanding how to tune collections can significantly impact latency, memory, and scalability. Here’s how to use Collections the right way: 🔹 1. Choose the Right Collection Type ArrayList → Fast reads, slower inserts in middle LinkedList → Rarely useful (avoid in most cases) HashMap → Fast key-based access (O(1)) TreeMap → Sorted data (O(log n)) ➡ Wrong choice = performance bottleneck. 🔹 2. Set Initial Capacity Smartly Avoid repeated resizing: new ArrayList<>(1000); new HashMap<>(1024); ➡ Reduces rehashing & memory reallocations. 🔹 3. Understand Load Factor (HashMap) Default = 0.75 Higher → less memory, more collisions Lower → more memory, better performance ➡ Tune based on use case. 🔹 4. Prefer ArrayList Over LinkedList Better cache locality Faster iteration Lower memory overhead ➡ LinkedList is rarely the right choice in real systems. 🔹 5. Use Concurrent Collections When Needed ConcurrentHashMap → thread-safe without full locking CopyOnWriteArrayList → read-heavy scenarios ➡ Avoid Collections.synchronized* unless necessary. 🔹 6. Avoid Unnecessary Boxing/Unboxing List<Integer> vs int[] ➡ Boxing adds memory + CPU overhead ➡ Use primitive arrays where performance is critical. 🔹 7. Use Streams Carefully Great for readability But avoid in tight loops / high-frequency paths ➡ Sometimes traditional loops are faster. 🔹 8. Optimize Iteration Patterns Prefer for-each over index loops Avoid nested loops on large datasets ➡ Think in terms of algorithmic complexity. 🔹 9. Remove Duplicates Efficiently Set<T> unique = new HashSet<>(list); ➡ O(n) vs O(n²) approaches. 🔥 Architect’s Takeaway Collections tuning is about small optimizations at scale. Done right, it leads to: ✔ Lower latency ✔ Better memory usage ✔ Higher throughput ✔ Scalable systems 💬 How are you tuning Java Collections in your high-performance applications? #100DaysOfJavaArchitecture #Java #Collections #PerformanceTuning #SystemDesign #JavaPerformance #TechLeadership
To view or add a comment, sign in
-
Explore related topics
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