Implemented LRU Cache in Java with LinkedHashMap

🚀 Day 96 of #100DaysOfCode Today’s challenge was all about implementing an LRU (Least Recently Used) Cache in Java — a problem that truly tests your understanding of data structures and memory optimization. 💡 🧩 Problem Statement: Design a data structure that supports: get(key) → Returns value if key exists, else -1 put(key, value) → Inserts or updates value Both should work in O(1) time complexity. It should automatically remove the least recently used entry when the cache exceeds its capacity. ⚙️ What I Implemented: ✅ Used LinkedHashMap with access order enabled. ✅ Overrode removeEldestEntry() to maintain fixed capacity. ✅ Ensured get() and put() operations are constant time. ✅ Tested the cache with sample inputs to confirm LRU behavior. 📘 Sample Output: When I executed the program, I got: {3=30, 1=10, 4=40} This confirmed that the oldest (least recently used) entry was correctly removed when the cache was full. 🧠 Concepts Strengthened: Understanding LinkedHashMap internals Efficient memory management O(1) data retrieval and replacement logic Practical use of overriding and encapsulation 🔥 Each day of this challenge pushes me closer to mastering clean, efficient, and optimized Java code. This one made me appreciate how real-world caching systems like browsers and databases manage performance. 💬 Next Goal: To explore advanced multithreading problems and optimize concurrent data structures. ✨ Almost at the finish line — Day 96/100! Every line of code is another step toward growth. 💪 #100DaysOfCode #Java #DataStructures #CodingChallenge #ProblemSolving #LinkedHashMap #SoftwareEngineering #LearningJourney #DeveloperCommunity

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories