🚀 Java 8 Streams – A Small Problem That Tests Big Concepts Today I revisited a classic interview question that seems simple but hides some heavy duty concepts: 👉 Find the last repeating character in a string using Java 8 Streams. Example: Input: "programming" Output: g (The repeated chars are 'r', 'g', 'm'. 'g' is the last one to appear in the original sequence.) Here is an elegant way to solve it: Java String input = "programming"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // Key: Maintains insertion order Collectors.counting() // Value: Frequency count )) .entrySet() .stream() .filter(e -> e.getValue() > 1) .reduce((first, second) -> second) // The "Last" logic .map(Map.Entry::getKey); result.ifPresent(System.out::println); ✨ Why this is a great test of fundamentals: It’s not just about the syntax it’s about what’s happening under the hood: It’s easy to write code that works it’s harder to write code that is both expressive and efficient. I’m curious how would you tackle this 😄? 1️⃣ Stick to the modern Streams approach? 2️⃣ Go back to a traditional for loop for potential performance gains? 3️⃣ Use a different collection entirely? #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #CleanCode #InterviewQuestion
FARHEEN .’s Post
More Relevant Posts
-
⚠️ Java Tip - Compound Operators Can Hide Type Conversions - Consider this code: int result = 20; result -= 2.5; System.out.println("result = " + result); // This DOES compile: // This does NOT compile: // result = result - 5.5; // possible lossy conversion from double to int // But this DOES compile: result -= 5.5; System.out.println("Hidden behavior here: result = " + result); Why does result -= 5.5 compile, but result = result - 5.5 does not? Because compound assignment operators in Java perform an implicit cast. Behind the scenes, this: result -= 5.5; is actually doing this: result = (int)(result - 5.5); Java silently casts the result back to int, potentially losing precision. That means: The compiler protects you in result = result - 5.5 But allows a silent narrowing conversion in result -= 5.5 This is not a bug it’s defined behavior in the Java Language Specification. If you're getting into programming, remember: - Understand what the language does for you automatically - Never assume implicit conversions are safe - Read compound operators carefully in numeric operations Small details like this 😉 separate someone who writes code… from someone who understands it. #Java #Programming #Backend #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
Java Compiled Or Interpreted. Is Java a compiled or interpreted language? The standard picture of Java is of a language that’s compiled into .class files before being run on a JVM. Lot of developers can also explain that bytecode starts off by being interpreted by the JVM but will undergo just-in-time (JIT) compilation at some later point. Here, however, many people’s understanding breaks down into a somewhat hazy conception of bytecode as basically being machine code for an imaginary or simplified CPU. In fact, JVM bytecode is more like a halfway house between human-readable source and machine code. In the technical terms of compiler theory, bytecode is really a form of intermediate language (IL) rather than actual machine code. This means that the process of turning Java source into bytecode isn’t really compilation in the sense that a C++ or a Go programmer would understand it, And javac isn’t a compiler in the same sense as gcc is — it’s really a class file generator for Java source code. The real compiler in the Java ecosystem is the JIT compiler. Some people describe the Java system as “dynamically compiled.” This emphasizes that the compilation that matters is the JIT compilation at runtime, not the creation of the class file during the build process. So, the real answer to “Is Java compiled or interpreted?” is “both.” I’m building a complete Senior Java Interview Guide. If this helps you, you can support the series here #Java #JavaStreams #SoftwareEngineering #Programming #CleanCode #Interviews #interviewGuide
To view or add a comment, sign in
-
-
📌 Switch Expressions in Java – Finally, No More Fall-Through Bugs 🚀 If you're preparing for modern Java interviews, you must know this feature. 👉 Introduced as preview in Java 12 👉 Became stable in Java 14 And it fixed one of the most annoying things in Java. 🤯 The Old Switch Problem switch(day) { case MONDAY: return 1; case TUESDAY: return 2; default: return 0; } Issues: - Verbose - Easy to forget break - Fall-through bugs - Not expressive 🚀 Switch Expression (Modern Way) int result = switch(day) { case MONDAY -> 1; case TUESDAY -> 2; default -> 0; }; Cleaner. Safer. More readable. No break. No accidental fall-through. 🔥 Multi-Line Case Example int result = switch(day) { case MONDAY, TUESDAY -> 1; case WEDNESDAY -> { System.out.println("Midweek"); yield 2; } default -> 0; }; Yes — yield returns a value from a block. 🔑 Final Thought Switch Expressions didn’t just improve syntax. They made switch: - Safer - More functional - More predictable Modern Java is about reducing accidental complexity. #Java #ModernJava #Java14 #SoftwareEngineering #InterviewPreparation
To view or add a comment, sign in
-
-
🚀 Day 8/30 – Java DSA Challenge 🔎 Problem 49: 35. Search Insert Position (LeetCode – Easy) Today I solved a classic Binary Search variation 🔥 🧠 Problem Summary Given: A sorted array of distinct integers A target value 🎯 Return: The index if target exists Otherwise, the index where it should be inserted ⚠️ Required Time Complexity → O(log n) 💡 Key Insight This is not just searching. It’s about finding the correct insert position while maintaining sorted order. 👉 If target is not found, the low pointer after binary search will automatically point to the correct insert index. 🔄 Correct Approach We modify standard binary search slightly: If nums[mid] == target → return mid If nums[mid] < target → search right Else → search left If loop ends → return low ⏱ Time Complexity O(log n) 📦 Space Complexity O(1) 📌 Pattern Learned ✔ Binary Search ✔ Lower Bound Concept ✔ Insert Position Logic ✔ Search in Sorted Array 🎯 Important Note Your previous code returns -1 if not found. But for this problem, we must return low instead of -1. That small modification makes it a different problem 💡 🔥 49 Problems Completed Day 8 = Binary Search variations practice Mastering Binary Search opens doors to: First/Last occurrence Lower/Upper bound Rotated arrays Search on answer problems 🚀 #Day8 #30DaysOfCode #Java #DSA #LeetCode #BinarySearch #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Java 8 Series – Day 3 Understanding Functional Interfaces In Day 2, we discussed Lambda Expressions. But here’s the important rule: A Lambda Expression can only be used with a Functional Interface. So today, let’s understand what that actually means. What is a Functional Interface? A Functional Interface is an interface that contains: Exactly ONE abstract method. That’s it. Example: @FunctionalInterface interface Calculator { int operate(int a, int b); } Now we can implement it using Lambda: Calculator add = (a, b) -> a + b; Why Only One Abstract Method? Because Lambda expressions provide the implementation of that single method. If there were multiple abstract methods, Java wouldn’t know which one the lambda is implementing. What is @FunctionalInterface? It is an optional annotation. If you accidentally add a second abstract method, the compiler will throw an error. It helps enforce the rule. Built-in Functional Interfaces in Java 8 Java 8 introduced many ready-made functional interfaces in the java.util.function package. Most commonly used ones: 1️⃣ Predicate Takes input, returns boolean Example: x -> x > 10 2️⃣ Function<T, R> Takes input, returns output Example: x -> x * 2 3️⃣ Consumer Takes input, returns nothing Example: x -> System.out.println(x) 4️⃣ Supplier Takes no input, returns output Example: () -> new Date() 5️⃣ UnaryOperator Takes one input, returns same type 6️⃣ BinaryOperator Takes two inputs, returns same type Real Interview Question: What is the difference between Predicate and Function? (Answer: Predicate returns boolean. Function returns any type.) Why Functional Interfaces Matter? They are the foundation of: • Lambda Expressions • Stream API • Method References • Functional programming in Java Without understanding Functional Interfaces, Java 8 will never feel complete. Tomorrow: Method References (::) Cleaner than Lambdas in many cases 👀 Follow the series if you're serious about mastering Java 8 🚀 #Java #Java8 #FunctionalInterface #BackendDeveloper #Coding #InterviewPreparation
To view or add a comment, sign in
-
🚀 Java 8 Streams – Word Frequency in a Sentence Here’s a classic interview-style problem 👇 🧩 Input: String str = "I am learning Streams API in JAVA JAVA"; 🎯 Goal: Count the frequency of each word using the power of Java Streams API. At first, we might think of using a Map and a loop. But with Java 8 Streams, we can make it expressive and concise. 💡 Solution: String str = "I am learning Streams API in JAVA JAVA"; Map<String, Long> wordCount = Arrays.stream(str.split(" ")) .collect(Collectors.groupingBy( word -> word, Collectors.counting())); wordCount.forEach((key, value) -> System.out.println(key + " : " + value)); 🔎 What’s happening here? • split(" ") → Breaks sentence into words • stream() → Creates a stream • groupingBy() → Groups identical words • counting() → Counts occurrences Simple. Clean. Powerful ✨ Want to make it better? You could: 1️⃣ Convert everything to lowercase to make it case-insensitive Problems like this show how beautifully Streams handle data transformation with minimal code. #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #LearningJourney #LearnWithMe
To view or add a comment, sign in
-
-
🚀 Java 8 Series – Day 2 Understanding Lambda Expressions Before Java 8, writing simple logic required a lot of boilerplate code. Example: Creating a Comparator Before Java 8: Comparator comp = new Comparator() { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } }; Too much code for a small logic, right? Now with Java 8 Lambda: Comparator comp = (s1, s2) -> s1.length() - s2.length(); One line. Same logic. Much cleaner. What is a Lambda Expression? A lambda expression is an anonymous function that: • Has no name • Has no modifier • Has no return type declaration • Can be passed as an argument It is mainly used to implement Functional Interfaces. Basic Syntax: (parameters) -> expression OR (parameters) -> { block of code } Examples: 1️⃣ No parameter () -> System.out.println("Hello") 2️⃣ Single parameter x -> x * x 3️⃣ Multiple parameters (a, b) -> a + b Why Lambda Was Introduced? • Reduce boilerplate code • Enable functional programming • Improve readability • Make collections processing powerful (Stream API) Where Are Lambdas Commonly Used? • Comparator • Runnable • Event handling • Stream API operations (filter, map, reduce) Interview Question: 1. Why can lambda be used only with Functional Interfaces? (Answer coming in Day 3 😉) In the next post, I’ll explain Functional Interfaces in depth with real interview examples. Follow the series if you're preparing for Java interviews 🚀 #Java #Java8 #Lambda #BackendDevelopment #Coding #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 6/30 – Java DSA Challenge 🔎 Problem 44: 992. Subarrays with K Different Integers (LeetCode – Hard) Today’s problem is a Hard-level extension of the sliding window counting pattern 🔥 🧠 Problem Summary Given an integer array nums and an integer k, 🎯 Return the number of subarrays that contain exactly k distinct integers. A subarray must be contiguous. 💡 Key Insight Counting exactly k distinct elements directly is difficult. So we use the powerful trick: ✅ Exactly(K) = AtMost(K) − AtMost(K − 1) This converts a Hard problem into two manageable sliding window problems. 🔄 Approach 1️⃣ Write a helper function atmost(k) → Count subarrays with at most k distinct elements 2️⃣ Use Sliding Window + HashMap: Expand right pointer Store frequency of elements If distinct count exceeds k, shrink from left Add (window size) to answer 3️⃣ Final Answer: atMost(k) − atMost(k − 1) ⏱ Time Complexity O(n) – Each element enters and leaves window once 📦 Space Complexity O(k) – HashMap stores at most k distinct elements 📌 Pattern Mastered ✔ Sliding Window – Variable Size ✔ HashMap Frequency Tracking ✔ Subarray Counting Pattern ✔ Exactly K = AtMost(K) − AtMost(K − 1) 🔥 Sliding Window Evolution So Far Minimum window length Fixed size window Binary subarrays with sum Nice subarrays (odd count) Subarrays with K distinct integers Now the pattern recognition is becoming automatic 💪 🔥 44 Problems Completed Day 6 = Hard-level Sliding Window conquered 🚀 #Day6 #30DaysOfCode #Java #DSA #LeetCode #SlidingWindow #HashMap #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Checking Anagrams Using Java Streams Most developers are familiar with the classic Anagram problem in programming. Two strings are called anagrams if they contain the same characters with the same frequency, but possibly in a different order. Example: String input1="earth"; String input2="heart"; Instead of using the usual character counting or sorting with arrays, I tried solving this using Java Streams. 🔎 Approach 1. Convert both strings to lowercase to ignore case differences. 2. Convert each string to a stream of characters using chars(). 3. Sort the characters using sorted(). 4. Convert each character to a String using mapToObj. 5. Join them back into a sorted string. 6. Compare the final sorted strings. 7. If both sorted strings are equal, the strings are anagrams. ⚙️ Key Stream Methods Used i. chars() - Converts the string to an IntStream of characters ii. sorted() - Sorts the characters iii. mapToObj() - Converts each character to String iv. Collectors.joining() - Combines them back into a string This approach shows how Java Streams can make data transformations concise and expressive. 💻 I’ve added my Java solution in the comments below. Please let me know if there are any other approaches I could try. #Java #JavaStreams #DSA #Coding #ProblemSolving #Developers #Programming #Anagrams
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