🚀 The 3 Java Maps That Outperformed HashMap (and Made My Code 3× Faster) Most Java developers swear by HashMap. It’s our go-to. Reliable. Familiar. Always the first choice. But here’s the thing 👉 HashMap isn’t always the best tool for the job. A few months ago, I was chasing down latency issues in a high-traffic service. After hours of profiling, the culprit wasn’t a slow DB, not network lag… It was a plain old HashMap. Turns out, using the wrong map in the wrong place can quietly crush performance. So I replaced it — and my code ran 3× faster. Here are the 3 hidden gems that changed everything 👇 1️⃣ WeakHashMap — The Self-Cleaning Cache 🧹 Most developers use HashMap for caching. But HashMap never forgets — objects stay until you manually remove them. That’s how memory leaks start. WeakHashMap fixes that by holding weak references to keys. Once a key is no longer referenced elsewhere, the GC wipes it automatically. Map<UserSession, String> cache = new WeakHashMap<>(); cache.put(new UserSession("u123"), "Active"); ✅ Perfect for temporary caches or listeners. ❌ Not for data that must persist. My service’s memory stabilized instantly after switching to it. 2️⃣ IdentityHashMap — When .equals() Betrays You 🧠 Ever had two different objects that look “equal”? HashMap treats them as the same key — because it uses .equals() and .hashCode(). IdentityHashMap doesn’t. It uses reference equality (==). Map<Object, String> map = new IdentityHashMap<>(); map.put(new String("Hello"), "A"); map.put(new String("Hello"), "B"); System.out.println(map.size()); // 2 This saved me from hours of debugging “why is my key missing?” nightmares. ✅ Great for frameworks, DI containers, parsers. ❌ Avoid if logical equality is intended. 3️⃣ EnumMap — The Ferrari of Fixed Keys 🏎️ If your keys are enums, stop using HashMap. Seriously. EnumMap is backed by an array, not hashes.That means O(1) lookups and zero overhead. enum Status { NEW, PROCESSING, DONE } Map<Status, String> map = new EnumMap<>(Status.class); map.put(Status.NEW, "Queued"); In my benchmarks, it was 2–3× faster than HashMap for enum keys. ✅ Type-safe, compact, and blazing fast. ❌ Only for enum-based keys. ⚡ Quick Decision Guide Goal Use This Map -------------------- ----------------- Auto-cleanup WeakHashMap Compare by reference IdentityHashMap Enum keys EnumMap General purpose HashMap 🧩 The Bigger Lesson We obsess over frameworks, cloud, and architecture — but sometimes raw data structures make the biggest difference. The right Map can reduce GC pressure, CPU load, and subtle equality bugs. The wrong one can silently waste thousands of cycles per second. So next time, pause before typing new HashMap<>(). There might be a better tool for that job. #Java #Performance #CleanCode #SystemDesign #HashMap #Collections #BackendDevelopment #ProgrammingTips
"3 Java Maps That Outperformed HashMap for Me"
More Relevant Posts
-
"🚀Day 43 of 50 – Java LeetCode Challenge" Today’s challenge was "20. Valid Parentheses" — a fundamental stack-based problem that strengthens your understanding of bracket matching and data structure usage. The goal is to determine whether a given string of parentheses is valid based on correct opening and closing order. ⏱ Today’s Task – Valid Parentheses 📝 Problem Statement: Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. ✅ A string is valid if: 1️⃣ Every open bracket has a corresponding closing bracket of the same type. 2️⃣ Brackets are closed in the correct order. 3️⃣ Every close bracket must have an open bracket before it. 🧪 Examples: Input: s = "()" Output: true ✅ Input: s = "()[]{}" Output: true ✅ Input: s = "(]" Output: false ❌ Input: s = "([])" Output: true ✅ Input: s = "([)]" Output: false ❌ 🔧 Constraints: 1 <= s.length <= 10⁴ s consists of parentheses only '()[]{}' 💻 My Java Solution: import java.util.*; class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put('}', '{'); map.put(']', '['); for (char c : s.toCharArray()) { if (map.containsKey(c)) { char top = stack.isEmpty() ? '#' : stack.pop(); if (top != map.get(c)) return false; } else { stack.push(c); } } return stack.isEmpty(); } } 🔍 Takeaways: ✅ Efficient use of a stack for bracket matching ✅ Clean implementation using a HashMap for bracket pairs ✅ Time complexity O(n) — single traversal through the string ✅ Space complexity O(n) — in worst case (all open brackets) 💡 Core Concepts: Stack data structure HashMap for mapping bracket pairs Iterative traversal and validation Balanced parenthesis logic 🎯 Day 43 completed — 7 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Stack #DataStructures #Day43 #JavaProgramming #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
💾 Heap vs Stack Memory in Java — Simplified! 🚀 In Java, memory is divided into two key areas — Heap and Stack. Understanding their roles helps you write efficient and bug-free code. 💡 🧠 Stack Memory: ➡️ Used for storing method calls and local variables. ➡️ Memory is automatically managed — created when a method starts, destroyed when it ends. ➡️ Fast and follows LIFO (Last In, First Out). ➡️ Example: int x = 10; 🔥 Heap Memory: ➡️ Used for storing objects and instance variables. ➡️ Managed by Garbage Collector (GC). ➡️ Slower but more flexible — data persists beyond method calls. ➡️ Example: Student s = new Student(); 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. Example Program: class Student { String name; // stored in Heap int age; // stored in Heap Student(String name, int age) { this.name = name; this.age = age; } } public class MemoryExample { public static void main(String[] args) { int marks = 95; // Stored in Stack (local variable) // Object stored in Heap, reference 's1' stored in Stack Student s1 = new Student("Akash", 22); System.out.println("Name: " + s1.name); System.out.println("Age: " + s1.age); System.out.println("Marks: " + marks); } } ✅ Program Output: Name: Akash Age: 22 Marks: 95 💡 Explanation: The Student object is created in Heap memory with values "Akash" and 22. The reference variable s1 (which points to that object) is stored in Stack memory. The local variable marks is also in the Stack. When main() finishes execution: The Stack frame is cleared automatically. The Student object in the Heap remains until the Garbage Collector removes it. 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. #Java #Programming #MemoryManagement #JavaDeveloper #CodingTips
To view or add a comment, sign in
-
🎯 Modern Java Null Handling: DTO vs Domain Objects - The Right Way! NullPointerException is still the #1 runtime error in Java applications. Let me share a battle-tested approach 👇 📌 The Problem We All Face: Your API receives JSON with nullable fields: { "userId": "123", "email": "user@example.com", "phoneNumber": null, "address": null } Traditional approach? Null checks everywhere! 😫 if (user.getPhone() != null) { if (!user.getPhone().isEmpty()) { sendSMS(user.getPhone()); } } 🎯 The Modern Solution: Layer 1️⃣ - DTO Layer (API Boundary) Keep it nullable for flexibility: public record UserRequest( String userId, String email, String phoneNumber, // nullable AddressDTO address // nullable ) Layer 2️⃣ - Domain Layer (Business Logic) Use Optional for clarity: public class User { private final String userId; private final String email; private final Optional<String> phoneNumber; private final Optional<Address> address; public void sendNotification(NotificationService service) { phoneNumber.ifPresent(phone -> service.sendSMS(phone, "Welcome!") ); address.ifPresentOrElse( addr -> service.sendMail(email, "Delivery: " + addr), () -> service.sendMail(email, "Add delivery address") ); } } Layer 3️⃣ - Safe Conversion public User toDomain() { return new User( userId, email, Optional.ofNullable(phoneNumber) .filter(p -> !p.isBlank()), Optional.ofNullable(address) .map(AddressDTO::toDomain) ); } 🚀 Real-World Benefits: ✅ No Null Checks: Code remains clean and readable ✅ Type Safety: Compiler tells you what's optional ✅ Self-Documenting: Optional clearly means "may not exist" ✅ Stream-Friendly: flatMap(Optional::stream) filters empties elegantly ✅ Testability: Mock-free unit tests, no null edge cases 💡 Golden Rules I Follow: 1️⃣ DTOs can be nullable (API contracts need flexibility) 2️⃣ Domain objects use Optional (business logic clarity) 3️⃣ Never return null from domain methods 4️⃣ Use Optional.ofNullable() at conversion boundaries 5️⃣ Combine with Stream API for powerful filtering ⚡ Power Combo Example: List<String> validPhones = users.stream() .map(User::getPhoneNumber) .flatMap(Optional::stream) // Magic! Filters empties .filter(phone -> phone.startsWith("+91")) .toList(); 🎓 Key Takeaway: The pattern isn't just about Optional - it's about separating concerns: DTOs handle external world (nulls exist) Domain handles business rules (Optional expresses intent) Conversion layer bridges them safely This follows DDD principles while keeping APIs backward-compatible! #Java #CleanCode #SoftwareArchitecture #DomainDrivenDesign #NullSafety #BestPractices #SpringBoot #BackendDevelopment #EnterpriseJava #CodeQuality #Optional #DTO #DDD #JavaDevelopers #SoftwareEngineering #TechTips #Programming #FullStackDevelopment
To view or add a comment, sign in
-
🚀 Top Java 11 Features You Should Know Java 11 (LTS) brings several powerful updates for developers. Here’s a quick breakdown of the highlights: 1️⃣ Run Java Files Without Compilation 💻 Previously, we had to compile Java programs with javac and then run the .class files. Now, for single-file programs, you can run directly: java MyProgram.java Java compiles temporarily in memory, executes it, and no .class file is created. ⚠️ This means only the source code is needed for sharing, not compiled bytecode. 2️⃣ New String Methods 🧩 Java 11 adds several handy utilities to the String class: " ".isBlank(); // true "Hello\nWorld".lines().forEach(System.out::println); " Java ".strip(); // "Java" (Unicode-aware) "Hi ".repeat(3); // "Hi Hi Hi " 3️⃣ Files Utility Enhancements 📂 Simpler file I/O with Files.readString() and Files.writeString(): Path path = Files.writeString(Files.createTempFile("demo", ".txt"), "Java 11"); String content = Files.readString(path); System.out.println(content); // "Java 11" 4️⃣ var in Lambda Parameters ⚡ var can now be used in lambda expressions, allowing annotations and improving readability: List<String> list = List.of("A", "B", "C"); list.stream() .map((var s) -> s.toLowerCase()) .forEach(System.out::println); Note: * var can also be used for local variables. * It is not a datatype, but a type inference reference — the compiler determines the actual type at compile time. * For local variables, var must be initialized at the time of declaration so the compiler can infer the type. * This feature for local variables was introduced in Java 10. 5️⃣ HTTP Client Standardization 🌐 The experimental HTTP client is now fully standardized in java.net.http: var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.github.com")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); Supports HTTP/1.1, HTTP/2, and WebSockets. 6️⃣ Garbage Collector Improvements 🧹 Epsilon GC: No-op GC for performance testing. ZGC: Low-latency garbage collector (experimental). 7️⃣ Deprecations & Removals 🧾 Java EE & CORBA modules removed (javax.xml.bind, java.activation) JavaFX removed from JDK (available separately) 8️⃣ Java Flight Recorder (JFR) ☁️ Integrated into OpenJDK for profiling and production monitoring. 9️⃣ Nest-Based Access Control 🏗️ Simplifies private access between nested classes, removing synthetic bridge methods. 🔟 TLS 1.3 Support ⚙️ Enhanced security and performance in JSSE with TLS 1.3. 🔥 Java enthusiasts, unite! 🔥 Love exploring juicy Java tips, tricks, and features? Follow me for insights that make coding fun and practical! 💻☕ Let’s level up your Java game! 🚀 #Java11 #JavaLTS #Programming #SoftwareDevelopment #CleanCode #JavaDevelopers #FullStackDevelopment #TechTrends #CodingTips #JavaFeatures #JavaFullStackDevelopment #BackendDevelopment #CodeWithMohan
To view or add a comment, sign in
-
Java Has Evolved — Here’s What Changed from JDK 8 to JDK 17 🚀 ☕ JDK 8 (2014) — The Modern Java Revolution Major Features: ✅ Lambda Expressions → Functional programming style ✅ Stream API → Process collections efficiently ✅ Functional Interfaces → @FunctionalInterface, Predicate, Function, etc. ✅ Default & Static Methods in Interfaces ✅ Optional Class → Avoid NullPointerException ✅ Date and Time API (java.time) → New modern date/time handling ✅ Nashorn JavaScript Engine ⚙️ JDK 9 (2017) — Modular Java Key Features: 🧩 Module System (Project Jigsaw) → module-info.java JShell (REPL) → Interactive Java shell Stream API Enhancements → takeWhile(), dropWhile(), iterate() Private Methods in Interfaces Factory Methods for Collections → List.of(), Set.of(), Map.of() ⚙️ JDK 10 (2018) — Developer Productivity Key Features: 🔹 Local Variable Type Inference → var keyword Garbage Collector Improvements (G1) Application Class-Data Sharing Parallel Full GC for G1 ⚙️ JDK 11 (2018) — LTS Release (Long-Term Support) Key Features: 🌐 New HttpClient API → Replaces old HttpURLConnection String Methods → isBlank(), lines(), strip(), repeat() Lambda Parameter Type Inference Removed Java EE & CORBA modules Single-file Source Code Execution → java Hello.java ⚙️ JDK 12 (2019) Key Features: 🧮 Switch Expressions (Preview) → switch usable as an expression JVM Constants API Shenandoah GC (low-pause-time GC) ⚙️ JDK 13 (2019) Key Features: 📜 Text Blocks (Preview) → Multi-line strings using """ Switch Expression Enhancements Reimplementation of Legacy Socket API ⚙️ JDK 14 (2020) Key Features: 🧱 Records (Preview) → Immutable data carriers (record Point(int x, int y)) 🕵️ Pattern Matching for instanceof (Preview) 🧍♂️ Helpful NullPointerException Messages Switch Expressions (Standardized) ⚙️ JDK 15 (2020) Key Features: 🧩 Sealed Classes (Preview) → Restrict which classes can extend a class Text Blocks (Standard) Hidden Classes EdDSA Algorithm Support (New Crypto) ⚙️ JDK 16 (2021) Key Features: 🧱 Records (Standard) 🕵️ Pattern Matching for instanceof (Standard) JEP 391: macOS/AArch64 support (Apple M1) Vector API (Incubator) Strong Encapsulation of JDK Internals ⚙️ JDK 17 (2021) — LTS Release Key Features: 🧩 Sealed Classes (Standard) 🕵️ Pattern Matching for switch (Preview) 🧱 Enhanced Pseudo-Random Number Generators (PRNG) Foreign Function & Memory API (Incubator) New macOS Rendering Pipeline (Metal API) Removed Deprecated RMI Activation, Applet API, etc.
To view or add a comment, sign in
-
💾 Tricky Java / Spring Boot Bug — The Serialization Saga aka “When Your Objects Refuse to Travel 😅” 🎯 Featuring: Microsoft Developers on a Friday evening… trying to send a POJO across microservices. 🧩 The Scene At Microsoft, a dev tried to send a User object from one service to another. Everything looked fine… until suddenly... 💥 java.io.NotSerializableException: com.microsoft.app.models.User That’s the moment when caffeine stopped working and reality hit hard. 😭 🧠 What Actually Happened? Serialization = Turning your Java object into bytes (so it can travel through a network, file, or message queue). Deserialization = Turning those bytes back into an object. In short: > Your object says, “I’m off to Azure Service Bus 🌩️” JVM replies, “Cool, but where’s your Serializable passport?” 🛂 ⚙️ The Bug (Common Mistake) class User { private String name; private String email; } When you try to send this object: 💥 Boom! NotSerializableException ✅ The Fix import java.io.Serializable; class User implements Serializable { private static final long serialVersionUID = 1L; private String name; private String email; } Now your POJO can safely travel across REST APIs, Kafka, or queues. 🚀 🌱 Bonus Tip (Spring Boot REST) Spring Boot uses Jackson for automatic JSON serialization: @GetMapping("/user") public User getUser() { return new User("Rudra", "rudra@microsoft.com"); } Jackson converts this to JSON behind the scenes. But beware 👇 ⚠️ Circular references (e.g., bidirectional JPA) ⚠️ Missing @JsonIgnore on sensitive data 🕵️ Debugging Tips 🔍 Check if your class implements Serializable 🔍 Look for non-serializable nested objects 🔍 Verify serialVersionUID after class changes 🔍 Enable spring.jackson.serialization logs for REST 🔍 Use @JsonIgnore wisely to avoid recursion ✅ Quick Checklist ☑️ Implement Serializable for objects that need persistence or transmission ☑️ Always add serialVersionUID ☑️ Use DTOs instead of entities for APIs ☑️ Mark sensitive fields as transient ☑️ Validate JSON mapping with ObjectMapper 💬 Real Talk At Microsoft, one dev said: > “My POJO refused to travel without a passport… Turns out, that passport was Serializable.” 😅 Serialization — simple in theory, chaotic in production. #Java #SpringBoot #Serialization #Microsoft #Microservices #Debugging #CodeHumor #Developers #TrickyBugs #CleanCode #JavaDevelopers #TechHumor #BackendDevelopment
To view or add a comment, sign in
-
🔥 Mastering Java HashMap — A Must-Know for Every Backend Developer! If you’re preparing for Java/Spring Boot interviews, HashMap is guaranteed to show up. It appears simple, but its internals reveal some of the most important concepts in Java collections and performance tuning. Here’s a clean, interview-ready breakdown 👇 --- ✅ 1. What is a HashMap? A key–value data structure offering O(1) average lookup time. Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); --- ✅ 2. How HashMap Works Internally HashMap uses hashing: The key’s hashCode() determines the bucket index. Keys with the same index go to the same bucket. In JDK 8+, collision chains may turn into a Red-Black Tree for faster lookups. --- ✅ 3. What Happens During Collisions? Entries form a Linked List. If collisions in a bucket exceed 8, it converts into a balanced tree. Performance: Linked list → O(n) Tree → O(log n) --- ✅ 4. Default Capacity & Load Factor Capacity: 16 Load Factor: 0.75 When 75% capacity is crossed → HashMap resizes and spreads entries into new buckets (rehashing). --- ✅ 5. Why HashMap Is Not Thread-Safe Because it’s not synchronized. Multiple threads modifying it may cause: Inconsistent data Data loss Race conditions For concurrency: use ConcurrentHashMap. --- ✅ 6. Can HashMap Store Null? ✔ One null key ✔ Multiple null values --- ✅ 7. HashMap vs Hashtable Feature HashMap Hashtable Thread-Safe ❌ No ✔ Yes Null Allowed ✔ Yes ❌ No Performance Faster Slower --- ✅ 8. What is Rehashing? During resize, all entries are re-distributed across a new array using their updated hash indices. --- ✅ 9. Time Complexity Best/Average: O(1) Worst: O(log n)** (tree buckets)** --- 🎯 Follow-Up Interview Questions 🔹 Q1: What if all keys have the same hash code? All entries land in one bucket → structure becomes a chain/tree → performance drops. --- 🔹 Q2: How does ConcurrentHashMap ensure thread safety? Uses fine-grained locking & CAS Only a small portion of the map locks during updates. --- 🔹 Q3: putIfAbsent() vs computeIfAbsent() map.putIfAbsent("key", "value"); map.computeIfAbsent("key", k -> getValue(k)); putIfAbsent() → inserts only if key is absent computeIfAbsent() → calculates & inserts lazily --- 🚀 Final Thoughts HashMap looks simple but its internals—hashing, collisions, rehashing, and concurrency—are foundational for clearing Java interviews and writing high-performance applications. --- #Java #JavaDeveloper #HashMap #CollectionsFramework #JavaInterview #BackendDevelopment #SpringBoot #CodingInterview #DSA #SystemDesign #TechLearning #ProgrammersLife #SoftwareEngineering #CareerGrowth #LearnJava #JavaCommunity
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
WeakHashMap is best among these three.