Multimap in Java:- In Java, a Multimap is a collection that maps a single key to multiple values. Unlike a standard java.util.Map, which associates each key with exactly one value, a Multimap allows you to store a "one-to-many" relationship efficiently. It is important to note that Multimap is not part of the standard Java Development Kit (JDK). It is primarily provided by popular third-party libraries like Google Guava and Apache Commons Collections. 1. Conceptual Difference Guava's Multimap is the industry standard. It provides two main sub-interfaces: ListMultimap: Uses a List to store values. It allows duplicate values for the same key and maintains insertion order. Implementation: ArrayListMultimap, LinkedListMultimap. SetMultimap: Uses a Set to store values. It does not allow duplicate values for the same key. Implementation: HashMultimap, TreeMultimap. Example using Guava: ListMultimap<String, String> multimap = ArrayListMultimap.create(); multimap.put("Fruit", "Apple"); multimap.put("Fruit", "Banana"); multimap.put("Vegetable", "Carrot"); // Returns [Apple, Banana] List<String> fruits = multimap.get("Fruit"); // Returns 3 (total entries) int totalEntries = multimap.size(); B. Apache Commons Collections Apache uses the MultiValuedMap interface. Implementation: ArrayListValuedHashMap, HashSetValuedHashMap. 3. The "Native" Java Way (Java 8+) If you don't want to add a third-party library, you can achieve Multimap behavior using a standard Map<K, Collection<V>> combined with the computeIfAbsent method introduced in Java 8. Standard JDK Implementation: Map<String, List<String>> manualMultimap = new HashMap<>(); // Adds "Apple" to the list under "Fruit", creating the list if it doesn't exist manualMultimap.computeIfAbsent("Fruit", k -> new ArrayList<>()).add("Apple"); manualMultimap.computeIfAbsent("Fruit", k -> new ArrayList<>()).add("Banana"); 4. Why use a Multimap library? While the computeIfAbsent approach works, using a dedicated library like Guava offers several advantages: Safety: get(key) returns an empty collection instead of null, avoiding NullPointerException. Cleanliness: You don't have to manually initialize collections or check if a key exists. Powerful Views: Methods like asMap() return a view of the Multimap as a Map<K, Collection<V>>, and entries() returns a flattened collection of all key-value pairs. Automatic Cleanup: If you remove the last value for a key, the key is typically removed from the map automatically. #java #javascript #python #csharp #automationtesting
Java Multimap: Guava vs Apache Commons Collections
More Relevant Posts
-
🚀 Java Practice: Custom Exception Handling I’ve been strengthening my core Java skills by practicing Custom Exception Handling, and here’s a small program I built based on a real-world scenario — Driving License Eligibility System. 💡 Concept Used: User-defined (custom) exceptions Exception propagation using throws Handling exceptions with try-catch Real-time validation logic 📌 Scenario: The program checks whether a person is eligible for a driving license based on age: ✅ 18–65 → Eligible ❌ Below 18 → UnderAgeException ❌ Above 65 → OverAgeException ⚙️ What I implemented: Created two custom exception classes: UnderAgeException OverAgeException Used meaningful error messages by overriding getMessage() Structured the program using multiple classes for clarity and modularity 🎯 Key Learning: Custom exceptions help in creating more readable, maintainable, and real-world oriented programs instead of relying only on predefined exceptions. 📚 This practice improved my understanding of how Java handles errors and how we can control program flow effectively. package exception; import java.util.Scanner; public class Goi_Custum_Exception { public static void main(String[] args) { GovOFKarnataka gk = new GovOFKarnataka(); gk.init(); } } class GovOFKarnataka{ void init() { Rto r = new Rto(); r.acceptInput(); try { r.verify(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); } } } class Rto{ int age; void acceptInput() { Scanner scan=new Scanner(System.in); System.out.println("Enter age: "); age=scan.nextInt(); } void verify() throws Exception{ if(age>=18&&age<=65) { System.out.println("Eligible for Driving Licence 🤩"); } else if(age>=65){ Exception oa = new OverAgeException(); throw oa; } else { Exception ua = new UnderAgeException(); throw ua; } } } class UnderAgeException extends Exception{ @Override public String getMessage() { return "Under Age Come After 18"; } } class OverAgeException extends Exception{ @Override public String getMessage() { // TODO Auto-generated method stub return "Over age you can go on others vehicle 😊"; } }
To view or add a comment, sign in
-
🚀🎊Day 78 of 90 – Java Backend Development ✨🎆 A Memory Leak in Java occurs when objects are no longer being used by the application, but the Garbage Collector (GC) is unable to remove them from the heap memory because they are still being unintentionally referenced. Even though Java has automatic memory management, a leak will slowly consume the available heap space until the JVM throws an OutOfMemoryError (OOM), causing the application to crash. 👉1. How it happens (The "GCRoot" Problem) In Java, an object is eligible for garbage collection if it is "unreachable." The GC starts from GC Roots (like local variables in the active thread or static variables) and traces all references. i) Normal Behaviour: When a method finishes, its local variables are cleared, the objects they pointed to become unreachable, and the GC reclaims the memory. ii) The Leak: An object is "logically" dead (your code doesn't need it anymore), but a "physically" live reference still exists (e.g., a forgotten item in a static List). Because a path still exists from a GC Root, the GC assumes the object is still important and leaves it alone. 👉 2. Common Causes in Java 👉Static Collections Static variables live for the entire lifetime of the JVM. If you add objects to a static List or Map and never remove them, they will stay in memory forever. public class Cache { private static Map<String, Object> map = new HashMap<>(); // If we never call map.remove(), this grows until OOM } 👉Unclosed resources: Connections to databases, files, or network sockets consume memory. If you don't call .close() (or use try-with-resources), the underlying native buffers may leak. 👉Inner classes: Non-static inner classes hold an implicit reference to their outer class. If the inner class object is passed around or stored, the outer class cannot be garbage collected, even if it's no longer used. 👉 Improper equals() and hashCode(): If you use custom objects as keys in a HashMap but don't implement equals() and hashCode() correctly, the Map won't find the duplicate keys. Instead, it will keep adding new entries every time you "update" a value, leading to a silent leak. 👉3. Symptoms of a memory Leak i) Performance Degradation: The GC runs more and more frequently (and takes longer) as it struggles to find free space, leading to "Stop-the-world" pauses. ii) Increased Memory Usage: The "Old Gen" (Tenured) space of the heap shows a steady upward trend in a sawtooth pattern that never returns to its baseline. iii) OutOfMemoryError: The application eventually crashes with java.lang.OutOfMemoryError: Java heap space. 👉 4. How to Detect and Fix To identify a leak, you need to look "inside" the JVM: i)Heap Dumps: Take a snapshot of the memory using jmap or via your IDE. ii)Analysis Tools: Use tools like Eclipse MAT (Memory Analyzer) or VisualVM. These tools show you which objects are taking up the most space and, more importantly, the "Path to GC Root" that is keeping them alive.
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 32 Today I revised LinkedHashMap in Java, an important Map implementation that maintains insertion order along with key-value storage. 📝 LinkedHashMap Overview LinkedHashMap is a class in java.util that implements the Map interface and extends HashMap. It stores data in key → value pairs while maintaining the order of insertion. Key Characteristics: • Stores unique keys and duplicate values allowed • Maintains insertion order • Allows one null key and multiple null values • Extends HashMap → inherits hashing benefits • Not thread-safe (use Collections.synchronizedMap() if needed) 💻 Declaration public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> • K → Key type • V → Value type ⚙️ Example LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); map.put("A", 1); map.put("B", 2); map.put("A", 3); // Updates value, order unchanged System.out.println(map); // Output: {A=3, B=2} ⚙️ Internal Working (Important) • Uses HashMap (hashing) for fast operations • Maintains a doubly linked list of entries • Each node contains: → Key → Value → Next (next node reference) → Previous (previous node reference) This is why it preserves insertion order 🏗️ Constructors Default LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); With Capacity + Load Factor LinkedHashMap<String, Integer> map = new LinkedHashMap<>(20, 0.75f); From Existing Map LinkedHashMap<String, Integer> map = new LinkedHashMap<>(existingMap); 🔑 Basic Operations Adding Elements: • put(key, value) → Adds while maintaining order Updating Elements: • put(key, newValue) → Replaces value (order unchanged) Removing Elements: • remove(key) → Deletes mapping 🔁 Iteration for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } 💡 Key Insight LinkedHashMap is widely used when you need: • Maintain insertion order + fast access (O(1)) • Predictable iteration order (unlike HashMap) • Implementing LRU cache (using access order mode) • Storing configurations or logs where order matters Understanding LinkedHashMap helps in scenarios where order + performance both are important, making it very useful in real-world backend systems. Day 32 done ✅ — consistency is becoming your strength 💪🔥 #Java #JavaLearning #LinkedHashMap #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
🚀🎊Day 86 of 90 – Java Backend Development ✨🎆 In Java, an Enum (short for "enumeration") is a special data type used to define a collection of constants. Think of it as a way to create a fixed list of predefined values that a variable can hold—like the days of the week, compass directions, or the states of a process. Before enums were introduced in Java 5, developers used public static final constants, which were prone to errors and lacked type safety. Enums solved this by making the code more readable and robust. 👉1. Basic syntax: Defining an enum is similar to defining a class, but you use the enum keyword. By convention, enum constants are written in uppercase. enum Level { LOW, MEDIUM, HIGH } You can then use this enum in your code like this: Level myVar = Level.MEDIUM; 👉2. Why use enums? Type Safety: You can't accidentally assign a value that isn't part of the enum (e.g., you can't set a Level to "SUPER_HIGH" if it isn't defined). i) Readability: It makes it clear to anyone reading your code what the allowed options are. ii) Switch Statements: Enums work beautifully with switch blocks, making logic branching much cleaner. 👉3. Enums are classes: In Java, enums are more powerful than in many other languages because they are effectively classes. This means they can have: i) Fields: To store additional data for each constant. ii) Methods: To perform actions based on the constant. iii) Constructors: To initialize those fields (though they are always private or package-private). 👉Code explanation enum TrafficLight { RED("STOP"), YELLOW("CAUTION"), GREEN("GO"); private String action; // Constructor TrafficLight(String action) { this.action = action; } public String getAction() { return this.action; } } 👉4. Useful built-in methods: Every Java enum automatically inherits methods from the java.lang.Enum class: i) values() ----->Returns an array of all constants in the enum. ii) ordinal() ----->Returns the index of the constant (starting at 0). iii) valueOf(String)------>Returns the enum constant with the specified string name. 👉5. When to avoid them: While enums are great for fixed sets of data, don't use them if the list of values needs to change at runtime (e.g., a list of users or products from a database). Enums are strictly for compile-time constants. #Java #Enums
To view or add a comment, sign in
-
-
🚀🎊Day 71 of 90 – Java Backend Development ✨🎆 In Java, a Stream is not a data structure; it’s a powerful way to process collections of objects in a functional style. Introduced in Java 8, the Stream API allows you to chain together high-level operations to perform complex data processing with very little code. Think of a stream like a conveyor belt in a factory. Data flows from a source, passes through various stations (filters, mappers), and eventually ends up as a finished product. 👉 1. How a Stream works A stream pipeline generally consists of three main parts: i) A Source: This provides the data. Usually, this is a Collection (like a List or Set), an array, or an I/O channel. ii) Intermediate Operations: These transform the stream into another stream (e.g., filter, map, sorted). They are lazy, meaning they don't execute until a terminal operation is called. iii) A Terminal Operation: This produces a result or a side effect (e.g., collect, forEach, reduce, count). Once this is called, the stream is "consumed" and cannot be used again. 👉2. Key characteristics: i)Declarative: You describe what you want to achieve (e.g., "filter even numbers") rather than how to do it (e.g., writing a for loop with an if statement). ii) Pipelining: Most stream operations return a new stream, allowing operations to be chained. iii) Internal Iteration: Unlike a for-each loop where you control the iteration (external), the Stream API handles the iteration for you behind the scenes. iv) Non-Storage: A stream does not store data; it simply moves data from a source through a pipeline of computational steps. 👉3. Code example: Suppose you have a list of names and you want to find names starting with "A," convert them to uppercase, and put them in a new list. The Stream Way (Functional): List<String> result = names.stream() .filter(n -> n.startsWith("A")) // Intermediate .map(String::toUpperCase) // Intermediate .collect(Collectors.toList()); // Terminal 👉4. Why use them? Streams make your code more readable and maintainable. They also make it incredibly easy to perform parallel processing. By simply changing .stream() to .parallelStream(), Java will attempt to split the workload across multiple CPU cores automatically. #Stream #Collections
To view or add a comment, sign in
-
-
🚀 Understanding Generics in Java – Write Flexible & Type-Safe Code If you’ve ever worked with collections like List or Map, you’ve already used Generics — one of the most powerful features in Java. 🔹 What are Generics? Generics allow you to write classes, interfaces, and methods with a placeholder for the data type. This means you can reuse the same code for different data types while maintaining type safety. 🔹 Why use Generics? ✔️ Eliminates type casting ✔️ Provides compile-time type safety ✔️ Improves code reusability ✔️ Makes code cleaner and more readable 🔹 Simple Example: List<String> names = new ArrayList<>(); names.add("Sneha"); // names.add(10); ❌ Compile-time error 🔹 Generic Class Example: class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹 🔥 Advanced Concepts Explained 🔸 1. Bounded Types (Restricting Types) You can limit what type can be passed: class NumberBox<T extends Number> { T value; } 👉 Only Integer, Double, etc. are allowed (not String) 🔸 2. Wildcards (?) – Flexibility in Collections ✔️ Unbounded Wildcard List<?> list; 👉 Can hold any type, but limited operations ✔️ Upper Bounded (? extends) List<? extends Number> list; 👉 Accepts Number and its subclasses 👉 Used when reading data ✔️ Lower Bounded (? super) List<? super Integer> list; 👉 Accepts Integer and its parent types 👉 Used when writing data 💡 Rule: PECS → Producer Extends, Consumer Super 🔸 3. Generic Methods public <T> void print(T data) { System.out.println(data); } 👉 Works independently of class-level generics 🔸 4. Type Erasure (Important for Interviews) Java removes generic type info at runtime: List<String> → List 👉 No runtime type checking 👉 Only compile-time safety 🔸 5. Multiple Bounds <T extends Number & Comparable<T>> 👉 A type must satisfy multiple conditions 🔸 6. Restrictions of Generics ❌ Cannot use primitives (int, double) → use wrappers ❌ Cannot create generic arrays ❌ Cannot use instanceof with generics 💡 Final Insight: Generics are not just a feature—they are a design tool that helps build scalable, reusable, and maintainable applications. Mastering advanced concepts like wildcards and type erasure can set you apart as a strong Java developer. #Java #Generics #AdvancedJava #Programming #JavaDeveloper #Coding #TechInterview
To view or add a comment, sign in
-
🚀 Today I dived deep into Exception Handling in Java! Have you ever seen a "software not responding" popup or had an app suddenly crash?,. That is often because of an unhandled exception. What is an Exception? In Java, an exception is an unusual event that occurs during the runtime (execution) of a program,,. It is usually triggered by faulty user input—like trying to divide a number by zero or providing a string when a number is expected,,. If these aren't handled, they lead to abrupt termination, which ruins the user experience and can cause significant losses for a company,. How it works behind the scenes: When a problem occurs, the JVM automatically creates an Exception Object,. This object contains the "What" (type of error), "Where" (line number), and "Why" (the reason),. If we don't catch it, the Default Exception Handler prints the error and stops the program immediately,. The Solution: Try-Catch Blocks To ensure normal termination, we follow three simple steps: 1.Identify risky lines of code where a problem might occur,. 2.Place that code inside a try block,. 3.Write a catch block to intercept the exception object and handle it gracefully,. Pro Tip: The Order of Catch Blocks Matters! ⚠️ You can have multiple catch blocks for different errors (like ArithmeticException or ArrayIndexOutOfBoundsException),. However, you must always put specific exceptions first and the general Exception class last,. If you put the general one first, the specific ones become unreachable code because the general class has the capability to catch everything. Code Example: import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Connection established."); try { // Step 1 & 2: Identify and wrap risky code, System.out.print("Enter numerator: "); int a = scan.nextInt(); System.out.print("Enter denominator: "); int b = scan.nextInt(); int result = a / b; // Risky line: ArithmeticException if b=0 System.out.println("Result: " + result); } catch (ArithmeticException e) { // Step 3: Handle specific exception, System.out.println("Error: Please enter a non-zero denominator."); } catch (Exception e) { // General catch-all for other unexpected issues System.out.println("Some technical problem occurred."); } System.out.println("Connection terminated.");, } } Looking forward to exploring rethrowing and ducking exceptions tomorrow!. #Java #Coding #BackendDevelopment #ExceptionHandling #LearningJourney #SoftwareEngineering #TapAcademy
To view or add a comment, sign in
-
-
Spring & Spring Boot Annotations Every Java Developer Should Know If you're preparing for interviews or working on real-time projects, mastering these annotations is a must! 💡 @Primary-When multiple beans of the same type exist, this one gets autowired by default. @Order - Controls the order in which components are applied or loaded (e.g., filters or interceptors). @Scope-Defines bean scope: singleton (default), prototype, request, session, etc. @Qualifier-Helps resolve conflict when multiple beans of the same type are available by specifying which one to inject. Dependency Injection Annotations @Autowired-Automatically injects a dependency by type. Can be applied to constructors, fields, or setters. @Resource - JSR-250 standard. Injects by name (first), then by type. @Inject-JSR-330 standard. Functions like @Autowired, but without Spring-specific options like required=false. @Required-Ensures that a property must be set in Spring config. Throws error if not Initialized (now deprecated in favor of constructor injection). Spring Boot Annotations @SpringBootApplication-Combines @Configuration, @EnableAutoConfiguration, and @Component Scan in a single annotation to bootstrap a Spring Boot app easily. @EnableAutoConfiguration - Tells Spring Boot to auto-configure your application based on the dependencies present on the classpath. @Configuration Properties - Binds external configuration (like from application.properties) to a POJO and validates them using JSR-303/JSR-380. @Conditional0nClass-Loads a bean or configuration only if a specified class is available in the classpath. @Conditional0nMissingClass - Opposite of @ConditionalOnClass; activates if the class is not present. @Conditional0nBean - Loads configuration or beans only if a certain bean exists. @Conditional0nMissingBean-Loads the bean only if the specified bean is not present in the context. @Conditional0nProperty-Activates beans/config based on a property's presence and value. @EnableConfiguration Properties - Enables support for @Configuration Properties-annotated beans. @ConstructorBinding-Indicates that configuration properties should be bound using the constructor instead of setters. #Java #SpringBoot #Microservices #BackendDeveloper #InterviewPreparation #JavaDeveloper #Coding #TechCareers
To view or add a comment, sign in
-
💡 What is Java Heap Space and OutOfMemoryError (and how to avoid it) ? 1️⃣ What is Java Heap Space ❓ Java heap space refers to a section of memory used by the Java Virtual Machine (JVM) for runtime memory allocation of Java objects. When a Java application creates a new object, that object is always allocated in the heap space 2️⃣ What is OutOfMemoryError ❓ This error occurs when the Java application attempts to allocate a new object in the heap, but there is insufficient memory available. This can happen mainly due to: 1. Memory Leaks: Objects are no longer needed but are still referenced, preventing the garbage collector from reclaiming their memory 2. Excessive Object Creation: The application creates too many objects, consuming all available heap space. 3. Insufficient Heap Size: The default or configured maximum heap size (-Xmx JVM argument) is too small for the application's memory requirements. 3️⃣ How to avoid OutOfMemoryError ❓ 1. Know your application's max heap size. This is the limit after which the error occurs. Run the below command by placing your java application's process ID:- jcmd <process_id> VM.flags | findstr MaxHeapSize Sample output:- -XX:CICompilerCount=2 .... -XX:MaxHeapSize=1610612736 ..... The above sample output shows 1.6 GB of max heap size for a program. 2. Use Memory Profiler tools like VisualVM to check in real-time, if your app's memory usage is nearing the max heap size or not. 4️⃣ How to solve OutOfMemoryError ❓ 1. By using memory profiler tools like VisualVM:- 1.1. Identify Memory Leaks for analyzing object creation and heap dumps to identify objects that are unnecessarily retained and fix the underlying code issues. 1.2. Identify Excessive Object Creation and optimize it by reducing the number of objects created or their size if possible. 2. Increase Heap Size: The most common immediate solution is to increase the maximum heap size using the -Xmx JVM argument during running your java app, for example, -Xmx512m for 512 MB. Note: This should be the last resort as the default max heap size should be enough in most of the cases and the error should be solved by removing memory leaks and optimizing object creation as explained before. #JavaPerformance #Backend #Microservices #SoftwareArchitecture #TechSolutions #PerformanceOptimization #Programming #Software #SystemDesign #Java #IT #SpringBoot #Error #SoftwareEngineering
To view or add a comment, sign in
-
Most Java Devs use Log4j2. Only 5% use it correctly. If you’re still treating your logs as just "text files with timestamps," you’re missing out on the framework’s real power. Modern high-scale systems don’t just need logs—they need observable, high-performance telemetry. Here is how you move from Basic to Advanced with Log4j2: Level 1: Beyond System.out (The Junior Phase) Stop manual logging. Use structured levels and smart formatting. Log Hierarchy: Understand that DEBUG shouldn't be in Prod, and ERROR should actually mean "someone needs to wake up." The Pattern Layout: Use %d{ISO8601}, %t (thread), and %X (MDC context). If your logs don’t tell you who did what and where, they are useless. Level 2: Scalable Management (The Professional Phase) Don't let your server die because of a massive .log file. RollingFileAppender: Use SizeBasedTriggeringPolicy (e.g., 100MB) and TimeBasedTriggeringPolicy (Daily). Automatic Cleanup: Set a DefaultRolloverStrategy with a max value so you don't eat up the entire disk. Level 3: Zero-Latency Logging (The Architect Phase) In high-concurrency apps, logging can be your biggest bottleneck. Async Loggers: By using the LMAX Disruptor (lock-free inter-thread communication), Log4j2 can be 12x faster than Logback and 68x faster than the original Log4j. Batching: Configure your appenders to flush to disk in batches rather than on every single line. Your CPU will thank you. Level 4: The Elite Tier (Garbage-Free & Filtering) This is where the real pros live. Garbage-Free Mode: Since v2.6, Log4j2 can run without allocating temporary objects (no char[] or String fragments). This eliminates GC pauses caused by logging. Dynamic Lookups: Use ${ctx:userId} or ${env:ENV_NAME} to inject runtime data directly into your configuration. Markers: Tag specific events (e.g., PAYMENT_GATEWAY) so you can filter them instantly in ELK/Splunk without grepping through millions of lines. Rohan Magdum Are you still on Team Logback, or have you made the switch to Async Log4j2? Let’s talk performance in the comments...
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