Java Collection Map

A Map in Java is a key-value pair data structure where each key is unique and maps to a single value. Unlike other collections like List or Set, Map does not extend Collection since it works on key-value pairs.


Implementation

Ordering

Performance

Null Keys/Values

Use Case

HashMap

No order

O(1) (Fastest)

✅ 1 null key, multiple null values

General-purpose, fastest

LinkedHashMap

Insertion Order

O(1)

✅ 1 null key, multiple null values

Maintain insertion order

TreeMap

Sorted (Ascending by Key)

O(log N) (Red-Black Tree)

❌ No null keys,

✅ multiple null values

Sorted data access


HashMap:

import java.util.HashMap;
import java.util.Map;

public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(5, "Mango");
map.put(33, "Grape");
System.out.println(map); // Output: {1=Apple, 33=Grape, 5=Mango} (Order may vary)
}
}

Try it yourself

LinkedHashMap:

import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Apple");
map.put(5, "Mango");
map.put(33, "Grape");
System.out.println(map); // Output: {1=Apple, 5=Mango,33=Grape} (Preserves insertion order)
}
}

Try it yourself

TreeMap:

import java.util.TreeMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<>();
map.put(1, "Apple");
map.put(33, "Grape");
map.put(5, "Mango");
System.out.println(map); // Output: {1=Apple, 5=Mango,33=Grape} (Sorted by key)
}
}

Try it yourself

Iterating over a map:

import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Dog");
map.put(2, "Cat");
map.put(3, "Elephant");
map.forEach((key, value) -> System.out.println(key + " -> " + value));
}
}

Try it yourself

List Methods:

Commonly Used Methods of List Interface

Method

Description

put(K key, V value)

Adds a key-value pair

get(K key)

Retrieves value by key

remove(K key)

Removes an entry by key

containsKey(K key)

Checks if a key exists

containsValue(V value)

Checks if a value exists

size()

Returns number of key-value pairs

keySet()

Returns a Set of all keys

values()

Returns a Collection of all values

entrySet()

Returns a Set of all key-value pairs


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.