🚀 LinkedHashMap = Built-in LRU Cache in Java If you’ve ever implemented an LRU Cache in interviews, this is your shortcut 👇 What is it? LinkedHashMap maintains insertion order (or access order) using a doubly linked list + hash table. With a small tweak, it behaves exactly like an LRU Cache. Why use it? • No need to manually manage DLL + HashMap • O(1) get & put operations • Clean and interview-friendly implementation How it works (LRU mode) Set accessOrder = true → recently accessed items move to the end Example 👇 import java.util.*; class LRUCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); // accessOrder = true this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; // remove least recently used } } Usage 👇 LRUCache<Integer, String> cache = new LRUCache<>(3); cache.put(1, "A"); cache.put(2, "B"); cache.put(3, "C"); cache.get(1); // access → 1 becomes recent cache.put(4, "D"); // removes key 2 (LRU) Flow 🧠 1️⃣ Insert → goes to end 2️⃣ Access → moves to end 3️⃣ Capacity full → remove from start (LRU) Result Efficient LRU cache in just ~10 lines of code ✅ Rule of Thumb 👉 If interviewer asks LRU → First say DLL + HashMap, then optimize using LinkedHashMap 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #DSA #BackendDevelopment #SystemDesign #CodingInterview
Implementing LRU Cache in Java with LinkedHashMap
More Relevant Posts
-
🌟 Hello Shining Stars!!! 🙏 💡 Java Type Promotion Hierarchy (Must-Know for Developers) Understanding type promotion is key to avoiding subtle bugs in Java 👇 🔼 Hierarchy (Widening Conversion): byte → short → int → long → float → double char → int → long → float → double ⚡ Golden Rules: 👉 byte, short, and char are automatically promoted to int in expressions 👉 Result = largest data type in the expression 👉 ✅ Promotion (widening) is automatic 👉 ❌ De-promotion (narrowing) is NOT automatic — requires explicit casting 🚨 Edge Case Examples (Tricky but Important): byte a = 10; byte b = 20; byte c = a + b; // ❌ Compilation Error // a + b becomes int → cannot store in byte without casting int x = 130; byte b = (byte) x; // ⚠️ Explicit cast (data loss) // Output will be -126 due to overflow char ch = 'A'; System.out.println(ch + 1); // Output: 66 // 'A' → 65 → promoted to int 🧠 Method vs Constructor Promotion (Important Interview Point): void test(int x) { System.out.println("int method"); } void test(double x) { System.out.println("double method"); } test(10); // Calls int method (exact match preferred over promotion) 👉 In methods, Java allows type promotion during overload resolution 👉 But constructors don’t “prefer” promotion the same way — exact match is prioritized, and ambiguous cases can lead to compilation errors 🎯 Takeaway: Java silently promotes smaller types, but it never automatically demotes them — and overload resolution can surprise you! #Java #Programming #Developers #Coding #InterviewPrep #TechTips 👍 Like | 🔁 Repost | 🔄 Share | 💬 Comment | 🔔 Follow | 🤝 Connect to grow together
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
-
-
🗺️ HashMap vs TreeMap in Java If you are preparing for Java backend interviews, this is one of the most commonly asked questions. HashMap 1. Stores data in key–value pairs 2. No ordering of keys 3. Allows one null key 4. Average O(1) time for put() and get() 5. Uses hashing internally 6. Faster for general use TreeMap 1. Stores data in sorted order of keys 2. Does NOT allow null key 3. Time complexity O(log n) 4. Uses Red-Black Tree internally 5. Useful when sorted data is required Rule of thumb: Use HashMap when you need fast access and order doesn’t matter Use TreeMap when you need sorted data or range-based operations 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #SpringBoot #BackendDevelopment #JavaDeveloper #Programming #SoftwareEngineering #CodingInterview #DataStructures #HashMap #TreeMap #TechInterview
To view or add a comment, sign in
-
-
🔥 Day 14: Immutable Class (How String is Immutable in Java) One of the most important concepts in Java — especially for interviews 👇 🔹 What is an Immutable Class? 👉 Definition: An immutable class is a class whose objects cannot be changed once created. 🔹 Example: String String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello (not changed) 👉 Why Because String is immutable 🔹 How String Becomes Immutable? ✔ String class is final (cannot be extended) ✔ Internal data is private & final ✔ No methods modify the original object ✔ Any change creates a new object 🔹 Behind the Scenes String s1 = "Hello"; String s2 = s1.concat(" World"); System.out.println(s1); // Hello System.out.println(s2); // Hello World 👉 s1 remains unchanged 👉 s2 is a new object 🔹 Why Immutability is Important? ✔ Thread-safe (no synchronization needed) ✔ Security (safe for sharing data) ✔ Caching (String Pool optimization) ✔ Reliable & predictable behavior 🔹 How to Create Your Own Immutable Class? ✔ Make class final ✔ Make fields private final ✔ No setters ✔ Initialize via constructor only ✔ Return copies of mutable objects 🔹 Real-Life Analogy 📦 Like a sealed box — once created, you cannot change what’s inside. 💡 Pro Tip: Use immutable objects for better performance and safety in multi-threaded applications. 📌 Final Thought: "Immutability = Safety + Simplicity + Performance" #Java #Immutable #String #Programming #JavaDeveloper #Coding #InterviewPrep #Day14
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
-
-
🚀 Can you find the first non-repeating character in a string? Here’s a simple Java approach 👇 String str = "aabbcd"; for(int i = 0; i < str.length(); i++) { boolean unique = true; for(int j = 0; j < str.length(); j++) { if(i != j && str.charAt(i) == str.charAt(j)) { unique = false; break; } } if(unique) { System.out.println(str.charAt(i)); break; } } 💡 Output: c 🔍 How it works: For each character, we check if it appears anywhere else in the string If it appears → not unique ❌ If it does NOT appear → first non-repeating character ✅ 👉 Time Complexity: O(n²) 💭 Interview Insight: This question is commonly asked to test your understanding of: ✔ Strings ✔ Nested loops ✔ Logic building 📌 Bonus: Can you optimize this to O(n) using HashMap? 👀 Drop your approach in comments 👇 #Java #Coding #DSA #InterviewPrep #Developers #100DaysOfCode
To view or add a comment, sign in
-
🚀 Java Interview Trap: Why "finally" Can Hide Exceptions 🤯 This is a dangerous one that many developers miss Example: public class Test { public static void main(String[] args) { try { throw new RuntimeException("Error in try"); } finally { throw new RuntimeException("Error in finally"); } } } 👉 Output: Exception in thread "main" java.lang.RuntimeException: Error in finally 🤔Where did the original exception go? 💡 What’s happening? - Exception thrown in try ❌ - finally block executes - New exception in finally overrides the original 👉 Original exception is LOST 😱 🔥 Why this is dangerous? - You lose actual root cause - Debugging becomes very hard - Production issues become confusing ✅ Better Approach: try { throw new RuntimeException("Error in try"); } catch (Exception e) { throw e; // preserve original } finally { System.out.println("Cleanup done"); } ⚠️ Interview Twist: try { return 10; } finally { throw new RuntimeException("Oops"); } 👉 Method will NOT return 10 ❌ 👉 Exception will be thrown instead 😳 💥 Golden Rule: ❌ Never throw exceptions from finally ❌ Avoid return in finally ✅ Use it only for cleanup 🎯 Pro Tip: Use try-with-resources instead of complex finally blocks #Java #JavaInterview #CodingInterview #Developers #Programming #TechTips
To view or add a comment, sign in
-
⚡ 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
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
-
-
Interesting Java Interview Question Recently, an interviewer asked a very logical question: Why does Hashtable not allow null key or null value in Java? At first it sounds simple, but the logic behind it is interesting. In Hashtable, when we retrieve a value using get(key), the method returns null in two situations: 1. The key does not exist in the table 2. The key exists but its value is null If Hashtable allowed null values, the system would not be able to distinguish between these two cases. This ambiguity could create logical issues, especially since Hashtable is a synchronized (thread safe) collection. To avoid this confusion, the designers of Java decided that Hashtable will not allow null keys or null values. Example: import java.util.Hashtable; public class Demo { public static void main(String[] args) { Hashtable<String,String> table = new Hashtable<>(); table.put("A","Java"); // valid table.put("B",null); // throws NullPointerException } } In contrast, HashMap allows one null key and multiple null values, because it handles key existence checks differently. Interview questions like this really test how deeply we understand Java Collections internally, not just how to use them. #Java #JavaInterview #JavaCollections #Hashtable #HashMap #Learning #javaJob
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