Day 22/100 — Lambda Expressions ⚡ From 5 lines of anonymous class → to just 1 clean line using lambdas. Before: new Runnable() { public void run() { println("Hi"); } }; After: () -> println("Hi"); Same output. ~80% less code, more readability. 💡 Why it matters: Lambdas make your code concise, functional, and easier to maintain—especially when working with collections. 🔹 Common Forms: → No params: () -> code → One param: x -> code → Two params: (x, y) -> code 🔹 Examples: names.sort((a, b) -> a.length() - b.length()); names.forEach(n -> println(n)); names.removeIf(n -> n.length() < 4); 🎯 Challenge: Sort a list by length first, then alphabetically when lengths are equal 👇 names.sort((a, b) -> { if (a.length() == b.length()) { return a.compareTo(b); } return a.length() - b.length(); }); Clean. Powerful. Interview-ready. 🚀 #Java #Lambda #Java8 #CoreJava #100DaysOfCode #100DaysOfJava #Programming #Developers
Java Lambda Expressions Simplify Code
More Relevant Posts
-
🚀 Day 22/100 – DSA Challenge Today’s problem: Climbing Stairs (LeetCode | Easy | DP) The problem is simple: You can climb either 1 or 2 steps at a time. How many distinct ways are there to reach the top? 🔴 Approach 1: Recursion (Brute Force) 👉 At each step, you have 2 choices: Take 1 step Take 2 steps 📌 Java Code: class Solution { public int climbStairs(int n) { if (n <= 2) return n; return climbStairs(n - 1) + climbStairs(n - 2); } } ⚡ Complexity: Time: O(2ⁿ) ❌ (recomputes subproblems) Space: O(n) (recursion stack) 🟡 Approach 2: Memoization (Top-Down DP) 👉 Store results of subproblems to avoid recomputation 📌 Java Code: class Solution { public int climbStairs(int n) { int[] dp = new int[n + 1]; return helper(n, dp); } private int helper(int n, int[] dp) { if (n <= 2) return n; if (dp[n] != 0) return dp[n]; dp[n] = helper(n - 1, dp) + helper(n - 2, dp); return dp[n]; } } ⚡ Complexity: Time: O(n) ✅ Space: O(n) 🟢 Observation: This problem is essentially the Fibonacci sequence: f(n) = f(n-1) + f(n-2) 🎯 Key Learning: Start with recursion to understand the problem, then optimize using DP to eliminate overlapping subproblems. 📈 Day 22 done—getting better at recognizing DP patterns! #100DaysOfCode #DSA #DynamicProgramming #Java #CodingJourney
To view or add a comment, sign in
-
Day16:- Arrays A Journey with Frontlines EduTech (FLM) and Fayaz S ✒️An array in Java is a data structure used to store multiple values of the same data type in a single variable. ✒️Instead of creating many variables, we store them in one array. Without array:- int a = 10; int b = 20; int c = 30; With array:- int [] numbers = {10,20,30}; Syntax:- dataType[] = new new dataType [size]; Array Initialization and access:- ✒️Arrays can also be initialized with values directly. int[] num = {1,2,3,4,5}; ✒️You can access elements using their index (string Index 0) Looping through arrays:- ✒️You can use loops to traverse arrays. ✒️ Commonly using for or enhanced for loops. ex:- int [] arr = {10,20,30,}; for(int i = 0; i<arr.lenght; i++) { System.out.println(arr[i]); } Advantages of Arrays:- ✒️Arrays allow random access of elements using index. ✒️Arrays are easy to traverse and manipulate using loops. ✒️Arrays help in efficient memory allocation when the size is known. ✒️They store multiple values in a single variable, reducing code complexity. ✒️Arrays are faster in accessing and modifying data compared to some data structures. Two-Dimensional Arrays :- ✒️2D arrays are arrays of arrays. They are useful for matrix-like data representation. Syntax:- dataType[][] arrayName = new dataType[rows][columns]; #arrays #corejava #java #2darrays
To view or add a comment, sign in
-
-
You can brute force this in O(n²)… or think smart and finish in O(n). Day 71 — LeetCode Progress Problem: Number of Good Pairs Required: Given an array nums, return the number of pairs (i, j) such that: i < j nums[i] == nums[j] Idea: Instead of checking all pairs, count frequency of each number. If a number appears c times, it can form: c × (c - 1) / 2 pairs. Approach: Use a HashMap to store frequency of each number Traverse the array and build frequency map For each frequency c: Add c * (c - 1) / 2 to result Return the result Time Complexity: O(n) Space Complexity: O(n) Small problem, but a powerful pattern: Counting + combinations = huge optimization. #LeetCode #DSA #Java #HashMap #ProblemSolving #CodingJourney” Day 71 — LeetCode Progress Problem: Number of Good Pairs Required: Given an array nums, return the number of pairs (i, j) such that: i < j nums[i] == nums[j] Idea: Instead of checking all pairs, count frequency of each number. If a number appears c times, it can form: c × (c - 1) / 2 pairs. Approach: Use a HashMap to store frequency of each number Traverse the array and build frequency map For each frequency c: Add c * (c - 1) / 2 to result Return the result Time Complexity: O(n) Space Complexity: O(n) Small problem, but a powerful pattern: Counting + combinations = huge optimization. #LeetCode #DSA #Java #HashMap #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 7: Cracking the "Two Pointer" Pattern 🚀 Today, I dived into LeetCode 167 (Two Sum II) to master the Two Pointer technique! While the standard Two Sum problem is often solved with a Hash Map, a Sorted Array gives us a secret advantage. By using two pointers—one at the start and one at the end—we can find the target sum in $O(n)$ time and $O(1)$ space. No extra memory needed! 🧠 💡 Key Takeaway: The magic happens in the movement: Sum < Target? Move the left pointer to grab a larger value. Sum > Target? Move the right pointer to grab a smaller value. Pro Tip: Always watch out for 1-indexed requirements! Adding that +1 to your return indices is the difference between a "Wrong Answer" and "Accepted." ✅ 🛠️ The Logic (Java): Java while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } One week down, more patterns to go! Following the roadmap from the "25 DSA Patterns" series. 📈 #DSA #LeetCode #CodingChallenge #Java #TwoPointers #SoftwareEngineering #Consistency
To view or add a comment, sign in
-
-
Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
To view or add a comment, sign in
-
-
🚀 Day 21/100 – DSA Challenge Today’s problem: Daily Temperatures 🌡️ The task is to find how many days you have to wait for a warmer temperature. If no such day exists, return 0. 🔴 Brute Force Approach (O(n²)) 👉 For each day, check all future days until you find a warmer temperature. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (temperatures[j] > temperatures[i]) { result[i] = j - i; break; } } } return result; } } 🟢 Optimized Approach: Monotonic Stack (O(n)) 👉 Instead of checking every future day, use a stack to store indices and resolve them when a warmer day appears. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; Stack<Integer> st = new Stack<>(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && temperatures[i] > temperatures[st.peek()]) { int prevPos = st.pop(); result[prevPos] = i - prevPos; } st.push(i); } return result; } } ⚡ Complexity Comparison: Brute Force → O(n²) Optimized (Stack) → O(n) 🎯 Key Learning: Whenever you see “next greater element” type problems, think monotonic stack 🔥 📈 Day 21 done—consistency is the real win! #100DaysOfCode #DSA #Java #CodingChallenge #LearningJourney
To view or add a comment, sign in
-
Java is quietly becoming one of the best platforms for Gen-AI — and most teams haven't noticed yet. We're not just building APIs and microservices anymore. The real shift is AI calls, LLM logic, and vector search living right inside Spring Boot services — and Java is evolving fast to support all of it. 🔥 Java 26 just dropped in March 2026, and Java 25 (LTS) is already solid in production: Pattern matching for primitives — cleaner, less boilerplate Smaller object sizes — better memory usage out of the box Here's what's changing on the ground right now: ->LangChain4j + Spring Boot → building AI search pipelines in Java is actually enjoyable now. ->LLM responses + Java's type system → less guessing, fewer bugs, cleaner code -> Stream Gatherers → process AI response streams in real time, the right way Java gives you speed, safety, and stability that Python just can't match at enterprise scale. It's not a Python vs Java debate anymore — it's about picking the right tool for production. 💬 Are you already using LLMs inside your Java services? What does your stack look like? #Java #Java25 #Java26 #GenerativeAI #SpringBoot #LangChain4j #BackendEngineering #LLM #GenAI
To view or add a comment, sign in
-
Day 7 🚶♀️➡️ 🚶♀️➡️🚶♀️➡️🚶♀️➡️🚶♀️➡️🚶♀️➡️🚶♀️➡️ 🚀 Problem: Leetcode- Statement Merge Nodes In Between Zeros Given a linked list where nodes contain integers, the list is divided into segments by zeros. Merge all nodes between two zeros by summing their values, and replace the starting zero with the sum. Remove all other nodes in the segment, including the ending zero. 💡 Solving Approach: 1️⃣ Step 1: Traverse the list using a pointer start. 2️⃣ Step 2: Sum all values between two zeros using another pointer end. 3️⃣ Step 3: Replace the starting zero (start.val = sum) with the sum. 4️⃣ Step 4: Skip nodes in the segment by setting start.next = end.next. 5️⃣ Step 5: Move start to the next segment and repeat. 📊 Time Complexity: O(n) O(n) (Traverse the list once). 📊 Space Complexity: O(1) O(1) (No extra space used). #LinkedList #CodingChallenge #LeetCode #DataStructures #ProblemSolving #Java
To view or add a comment, sign in
-
-
Solved: Remove Duplicates from Sorted Array 🔍 Problem Summary: Given a sorted array, remove duplicates in-place such that each unique element appears only once and return the new length. 💡 Approach: ✔️ Used the Two Pointer technique ✔️ One pointer (index) tracks unique elements ✔️ Another pointer (j) scans the array ✔️ When a new element is found, move it forward 👨💻 Code (Java): public int removeDuplicates(int[] nums) { if (nums.length == 0) { return 0; } int index = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[index]) { index++; nums[index] = nums[j]; } } return index + 1; } ⚡ Key Learning: Understanding patterns is more important than memorizing solutions. Sorted array + duplicates → Two Pointer approach works efficiently. 📊 Complexity: ⏱ Time: O(n) 💾 Space: O(1) 📌 Improving step by step—consistency is the goal! #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Learning
To view or add a comment, sign in
-
-
Hi everyone 👋 Continuing the Spring Boot Validation Series Part 30👇 📌 Validation Annotation – @Pattern The @Pattern annotation is used to validate a field using a regular expression (regex) 👇 🔹 Why do we use @Pattern? Sometimes we need to validate format like: Email format Phone number Password rules Only alphabets / numbers 👉 @Pattern helps enforce these rules. 🔹 Simple Example - public class User { @Pattern(regexp = "^[a-zA-Z]+$") private String name; } 👉 Allows only alphabets 👉 If invalid → validation fails ❌ 🔹 Email Example - @Pattern(regexp = "^[A-Za-z0-9+_.-]+@(.+)$") private String email; 🔹 Important Point 👉 @Pattern works only with String fields 👉 It does NOT check null ❌ So often combined with: @NotNull @Pattern(regexp = "your-regex") private String field; 🔹 In simple words @Pattern checks if a value follows a specific format. 👉 🧠 Quick Understanding - Uses regex for validation - Works only on String - Used for format validation - Often combined with @NotNull or @NotBlank #SpringBoot #Java #Validation #PatternAnnotation #BackendDevelopment #LearningInPublic
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
That progression from verbose anonymous classes to lambdas is such a satisfying shift, Allaka. One thing I've noticed helps junior devs really internalize this is having them refactor older codebases, they immediately see where functional patterns reduce cognitive overhead. Your sorting comparator is a nice touch, though for readability in production I'd usually extract that logic into a Comparator.comparing chain. Clean examples though, keep it going.