#50DaysOfStreams – Day 2 & Day 3 Continuing my journey of solving one Java Stream problem daily for 50 days 💪 ✅ Day 2: Find Duplicate Elements in a List 🧩 Problem: Given a list of integers, find all elements that appear more than once. 💡 Solution: List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 2, 3, 6, 7, 3); Set<Integer> duplicates = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(entry -> entry.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toSet()); System.out.println(duplicates); ✅ Day 3: Find the Second Highest Number in a List 🧩 Problem: Given a list of integers, find the second highest number using Streams. 💡 Solution: List<Integer> list = Arrays.asList(10, 5, 20, 8, 25, 15); Optional<Integer> secondHighest = list.stream() .distinct() .sorted(Comparator.reverseOrder()) .skip(1) .findFirst(); secondHighest.ifPresent(System.out::println); Consistency > Motivation 🔥 See you tomorrow with Day 4! #Java #Streams #FunctionalProgramming #CodingChallenge #BackendDevelopment #100DaysOfCode
Java Streams Challenge: Duplicate Elements and Second Highest Number
More Relevant Posts
-
50DaysOfStreams – Day 4 ✅ Day 4: Find the First Non-Repeated Character in a String 🧩 Problem: Given a string, find the first non-repeating character using Java Streams. Solution: String input = "swiss"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, Collectors.counting() )) .entrySet() .stream() .filter(entry -> entry.getValue() == 1) .map(Map.Entry::getKey) .findFirst(); result.ifPresent(System.out::println); Output: w 🛠 Concepts Used: chars() mapToObj() groupingBy() LinkedHashMap (to maintain order) findFirst() See you tomorrow for Day 5 🔥 #Java #Streams #FunctionalProgramming #CodingChallenge #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚀 #WhyGoroutinesAreLightweight? 1️⃣ Very Small Initial Stack Size * A goroutine starts with ~2 KB stack (can grow dynamically). * A Java thread typically starts with ~1 MB stack (configurable, but large by default). 👉 That means you can run hundreds of thousands of goroutines in the same memory where you could only run thousands of threads. 2️⃣ #Managed by Go Runtime (Not OS) * Java threads = 1:1 mapping with OS threads. * Goroutines = M:N scheduler model This means: * Many goroutines (N) are multiplexed onto fewer OS threads (M). * Go runtime scheduler decides which goroutine runs. This reduces: * OS context switching cost * Kernel-level overhead 3️⃣ #CheapContextSwitching Switching between goroutines: * Happens in user space * Much faster than OS thread switching * Does not require kernel involvement Java threads: * Context switching handled by OS * More expensive 4️⃣ #EfficientBlockingModel When a goroutine blocks (e.g., I/O): * Go runtime parks it * Another goroutine runs on the same thread In Java: Blocking thread often blocks OS thread (unless using async frameworks) 5️⃣ #DynamicStackGrowth Goroutines: * Stack grows and shrinks automatically * Memory efficient Java threads: * Fixed stack size * Allocated upfront Summary Feature Goroutine Java Thread Stack Size ~2KB (dynamic) ~1MB (fixed) Scheduling. Go runtime OS Context Switching User-level Kernel-level Scalability. Massive Limited 🔥 Real Example You can easily spawn: for i := 0; i < 100000; i++ { go process() } Try doing that with 100,000 Java threads 😅 — you’ll likely run out of memory. #TechCareers #SoftwareEngineer #BackendEngineer #Developers #TechCommunity #CodingLife #golangdeveloper
To view or add a comment, sign in
-
-
Exception handling is one of those fundamentals that directly impacts how reliable a system feels in production. In Java, exception handling allows us to manage unexpected situations using try, catch, and finally blocks, ensuring the application does not fail abruptly and can recover or respond gracefully. In backend systems, this becomes essential when dealing with database operations, API calls, file handling, or user input. Proper exception handling helps maintain system stability, improves debugging, and ensures a better user experience even when things go wrong. It is also a common topic in interviews because it reflects how well a developer can write robust and maintainable code rather than just making things work. When designing exception handling in a project, how do you decide between handling an exception immediately versus propagating it to higher layers? #Java #JavaDeveloper #BackendDevelopment #ExceptionHandling #ProgrammingFundamentals #CleanCode #JavaInterview
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟵/𝟵𝟬: 𝗧𝗵𝗲 𝗦𝗲𝗰𝗿𝗲𝘁 𝗼𝗳 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮 𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗼𝗼𝗹 I dove into one of Java's smartest memory management features: the String Constant Pool (SCP). Understanding this is the difference between writing "working" code and "optimized" code. 𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗼𝗼𝗹? The String Pool is a special storage area in the Heap memory. When you create a String literal (e.g., "Hello"), Java checks the pool first. If it exists, it reuses the reference instead of creating a new object. This saves a massive amount of memory! 𝟮. 𝗧𝗵𝗲 == 𝘃𝘀 .𝗲𝗾𝘂𝗮𝗹𝘀() 𝗧𝗿𝗮𝗽 ==: Compares Memory Addresses (Are these the same object?). .𝗲𝗾𝘂𝗮𝗹𝘀(): Compares Content (Do these have the same characters?). String s1 = "Java"; // Stored in Pool String s2 = "Java"; // Points to the same object in Pool String s3 = new String("Java"); // Created in Heap (outside Pool) System.out.println(s1 == s2); // true (Same address) System.out.println(s1 == s3); // false (Different locations) System.out.println(s1.equals(s3)); // true (Same text) 𝟯. 𝗧𝗵𝗲 𝗶𝗻𝘁𝗲𝗿𝗻() 𝗠𝗲𝘁𝗵𝗼𝗱: What if you have a String in the Heap (like s3) and you want to move it into the Pool? Use s3.intern(). This method searches the pool for a matching string and returns its reference. String s4 = s3.intern(); System.out.println(s1 == s4); // true! Now they share the pool address. Always use String literals when possible to take advantage of the pool, and never use == to compare text content! #90DaysOfCode #JavaFullStack #PentagonSpace #JavaProgramming #StringPool #CleanCode #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
Day 45 — LeetCode Progress (Java) Problem: Intersection of Two Arrays Required: Given two integer arrays nums1 and nums2, return an array containing their unique intersection elements. Idea: Use a HashSet to efficiently track elements from the first array and check their presence in the second array. Approach: Create a HashSet to store all elements from nums1. Traverse nums1 and insert each element into the set. Initialize a list to store the intersection result. Iterate through nums2: If an element exists in the set: Add it to the result list. Remove it from the set to avoid duplicates. Convert the result list into an array and return it. Time Complexity: O(n + m) n = length of nums1 m = length of nums2 Space Complexity: O(n) #LeetCode #DSA #Java #HashSet #Arrays #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 73 / 100 Days of LeetCode Question: Check if Binary String Has at Most One Segment of Ones Given a binary string s, determine whether it contains at most one continuous segment of '1's. Solved in Java by checking whether the pattern "01" exists in the string. If "01" appears, it means a new segment of 1s starts after a 0, which violates the condition. This provides a clean and efficient solution. Consistency > perfection. Day 74 loading 🔥 #100DaysOfCode #LeetCode #Java #DSA #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Ever wondered how backend systems handle thousands of requests at the same time? The answer is **Multithreading**. Multithreading allows a program to execute multiple tasks concurrently using multiple threads, improving performance and responsiveness — especially in backend applications. To make this concept easier to understand, I created a **visual guide on Java Multithreading**. 📌 Topics covered in this PDF: • What is Multithreading • Thread Lifecycle in Java • Runnable Interface • Thread Synchronization • Thread Communication (wait, notify, notifyAll) • Daemon Thread • ExecutorService • Thread Pool & Fixed Thread Pool • Single Thread Executor • Future & Callable • Real World Backend Use Cases I tried to explain these concepts with **simple visuals and examples** so beginners can understand multithreading easily. 📄 Feel free to go through the slides. 💬 **Question:** Which multithreading concept do you find most confusing? #Java #Multithreading #JavaDeveloper #BackendDevelopment #Concurrency #SpringBoot #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Understanding static in Java — More Powerful Than It Looks While revisiting Core Java fundamentals, I explored how static works as a: • Static Variable • Static Method • Static Block At first, static feels simple. But in real-world backend systems, it plays a critical role. 1. Static Variable Shared across all objects of a class. Example: Company name shared by all employees. Only one copy exists in memory. 2. Static Method Belongs to the class, not the object. Called using the class name. Commonly used for utility logic and shared operations. 3. Static Block Executes only once when the class is loaded. Used for initializing configurations or shared resources. Why this matters in production systems: • Configuration management • Logging setup • Utility classes • Connection pools • Shared counters • Caching mechanisms Understanding static properly improves memory management and application design. Strong backend engineering starts with mastering how memory and class loading actually work. Curious to hear from experienced developers: Where have you seen static used effectively in production systems? #Java #CoreJava #BackendDevelopment #SoftwareEngineering #JVM #CleanCode #JavaDeveloper #TechCareers
To view or add a comment, sign in
-
-
#Day11 of #100DaysofCode Challenge ✨ 📚 Today I Learned: Important Java String & Character Methods While practicing Java, I studied some useful methods that help us clean, check, and modify text in real programs. 🔹 String Methods ✔ trim() Removes spaces at the beginning and end of a string. Example: " hello " → "hello" ✔ toLowerCase() / toUpperCase() Convert all letters to lowercase or uppercase. Example: "Java" → "JAVA" ✔ startsWith() Checks if a string begins with a specific word. Example: "https://google.com" starts with "https" → true ✔ endsWith() Checks if a string ends with a specific word. Example: "mail@gmail.com" ends with "@gmail.com" → true ✔ replace() Replaces all occurrences of a character or word. Example: "teh cat" → "the cat" ✔ replaceFirst() Replaces only the first occurrence. These methods are useful in: 👉 Form validation 👉 Cleaning user input 👉 Checking URLs or emails 🔹 Character Methods These work on single characters. ✔ isLetter() → Checks alphabet ✔ isDigit() → Checks number ✔ isWhitespace() → Checks space ✔ isUpperCase() / isLowerCase() → Check letter case ✔ toUpperCase() / toLowerCase() → Change case ✔ toString() → Convert char → string Useful for: 👉 Password validation 👉 Checking user input 👉 Parsing text Understanding basics clearly helps solve bigger problems later. Learning step by step every day 🚀 #Java #CodingJourney #DSA #Learning #Consistency #ccbp #NxtWave #Developer #JavaFullStack #LearningByDoing Rahul Attuluri
To view or add a comment, sign in
-
Day 14/100 – LeetCode Challenge 🚀 Problem: #169 Majority Element Difficulty: Easy Language: Java Approach: Sorting + Middle Element Time Complexity: O(n log n) Space Complexity: O(1) 🔍 Key Insight: The majority element appears **more than ⌊n / 2⌋ times** in the array. If we **sort the array**, the majority element must occupy the **middle position** because it appears more than half of the time. Therefore, the element at index **n/2** will always be the majority element. 🧠 Solution Brief: First sorted the array using `Arrays.sort()`. Since the majority element appears more than half of the array length, it will always be positioned at the middle index. Finally returned `nums[nums.length / 2]` as the majority element. 📌 What I Learned: Understanding problem constraints can simplify the solution significantly. Sometimes a simple observation (like majority occupying the middle after sorting) can avoid more complex implementations. #LeetCode #Day14 #100DaysOfCode #Java #DSA #Arrays #ProblemSolving #CodingJourney
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