0% found this document useful (0 votes)
42 views

Java Map Interface

A map is an interface that represents a mapping between a key and a value pair. Common map implementations are HashMap, TreeMap, and LinkedHashMap. The document then provides examples of how to use various map operations like put, get, remove, iterate, and sort entries.

Uploaded by

antimbhowal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Java Map Interface

A map is an interface that represents a mapping between a key and a value pair. Common map implementations are HashMap, TreeMap, and LinkedHashMap. The document then provides examples of how to use various map operations like put, get, remove, iterate, and sort entries.

Uploaded by

antimbhowal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

JAVA MAP INTERFACE

A map is an Java interface that represents a mapping between a key and a


pair value.
➔ A Map cannot contain duplicate keys and each key can map to at
most one value. Some implementations allow null key and null values
like the HashMap and LinkedHashMap, but some do not like
the TreeMap.
➔ The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
➔ There are two interfaces for implementing Map in java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.

Maps has the following classes:


➔ HashMap – It contains unique keys and can have one null key and
multiple null values. It does not maintain the order.
➔ LinkedHashMap – It contains unique elements and can have one null
key and multiple null values. It maintains the order.
➔ TreeMap – It contains unique elements in ascending order and does
not allow null keys and thus a NullPointerException is thrown.

How to create a Map


1. HashMap<String, Integer> map = new HashMap<String, Integer>();
2. TreeMap < Integer, String> map = new TreeMap<Integer, String>();
3. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,S
tring>();
Basic Map programs

1. Implementing HashMap Class

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

class Main {

public static void main(String[] args) {


// Creating a map using the HashMap
Map<String, Integer> numbers = new HashMap<>();

// Insert elements to the map


numbers.put("One", 1);
numbers.put("Two", 2);
System.out.println("Map: " + numbers);

// Access keys of the map


System.out.println("Keys: " + numbers.keySet());

// Access values of the map


System.out.println("Values: " + numbers.values());
// Access entries of the map
System.out.println("Entries: " + numbers.entrySet());

// Remove Elements from the map


int value = numbers.remove("Two");
System.out.println("Removed Value: " + value);
}
}

Output:
Map: {One=1, Two=2}
Keys: [One, Two]
Values: [1, 2]
Entries: [One=1, Two=2]
Removed Value: 2

2. Implementing TreeMap Class


import java.util.Map;
import java.util.TreeMap;

class Main {

public static void main(String[] args) {


// Creating Map using TreeMap
Map<String, Integer> values = new TreeMap<>();
// Insert elements to map
values.put("Second", 2);
values.put("First", 1);
System.out.println("Map using TreeMap: " + values);

// Replacing the values


values.replace("First", 11);
values.replace("Second", 22);
System.out.println("New Map: " + values);

// Remove elements from the map


int removedValue = values.remove("First");
System.out.println("Removed Value: " + removedValue);
}
}

Output:
Map using TreeMap: {First=1, Second=2}
New Map: {First=11, Second=22}
Removed Value: 11

3. Add elements to a HashMap


To add a single element to the hashmap, we use the put() method of
the HashMap class. For example,
import java.util.HashMap;
class Main {
public static void main(String[] args) {

// create a hashmap
HashMap<String, Integer> numbers = new HashMap<>();

System.out.println("Initial HashMap: " + numbers);


// put() method to add elements
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("HashMap after put(): " + numbers);
}
}

Output:

Initial HashMap: {}
HashMap after put(): {One=1, Two=2, Three=3}

4. Access HashMap Elements


We can use the get() method to access the value from the hashmap. For
example,
import java.util.HashMap;
class Main {
public static void main(String[] args) {

HashMap<Integer, String> languages = new HashMap<>();


languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);

// get() method to get value


String value = languages.get(1);
System.out.println("Value at index 1: " + value);
}
}

Output:
HashMap: {1=Java, 2=Python, 3=JavaScript}
Value at index 1: Java

We can also access the keys, values, and key/value pairs of the hashmap
as set views using keySet(), values(), and entrySet() methods respectively.
For example,
import java.util.HashMap;

class Main {
public static void main(String[] args) {
HashMap<Integer, String> languages = new HashMap<>();

languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);

// return set view of keys


// using keySet()
System.out.println("Keys: " + languages.keySet());

// return set view of values


// using values()
System.out.println("Values: " + languages.values());

// return set view of key/value pairs


// using entrySet()
System.out.println("Key/Value mappings: " + languages.entrySet());
}
}

Output:
HashMap: {1=Java, 2=Python, 3=JavaScript}
Keys: [1, 2, 3]
Values: [Java, Python, JavaScript]
Key/Value mappings: [1=Java, 2=Python, 3=JavaScript]

5. Change HashMap Value


We can use the replace() method to change the value associated with a
key in a hashmap. For example,
import java.util.HashMap;

class Main {
public static void main(String[] args) {

HashMap<Integer, String> languages = new HashMap<>();


languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("Original HashMap: " + languages);

// change element with key 2


languages.replace(2, "C++");
System.out.println("HashMap using replace(): " + languages);
}
}

Output:
Original HashMap: {1=Java, 2=Python, 3=JavaScript}
HashMap using replace(): {1=Java, 2=C++, 3=JavaScript}
6. Remove HashMap Elements
To remove elements from a hashmap, we can use the remove() method.
For example,
import java.util.HashMap;

class Main {
public static void main(String[] args) {

HashMap<Integer, String> languages = new HashMap<>();


languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);

// remove element associated with key 2


String value = languages.remove(2);
System.out.println("Removed value: " + value);

System.out.println("Updated HashMap: " + languages);


}
}

Output:
HashMap: {1=Java, 2=Python, 3=JavaScript}
Removed value: Python
Updated HashMap: {1=Java, 3=JavaScript}
7. Iterate through a HashMap
To iterate through each entry of the hashmap, we can use Java for-each
loop. We can iterate through keys only, vales only, and key/value
mapping. For example,
import java.util.HashMap;
import java.util.Map.Entry;

class Main {
public static void main(String[] args) {

// create a HashMap
HashMap<Integer, String> languages = new HashMap<>();
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);

// iterate through keys only


System.out.print("Keys: ");
for (Integer key : languages.keySet()) {
System.out.print(key);
System.out.print(", ");
}

// iterate through values only


System.out.print("\nValues: ");
for (String value : languages.values()) {
System.out.print(value);
System.out.print(", ");
}

// iterate through key/value entries


System.out.print("\nEntries: ");
for (Entry<Integer, String> entry : languages.entrySet()) {
System.out.print(entry);
System.out.print(", ");
}
}
}

Output:
HashMap: {1=Java, 2=Python, 3=JavaScript}
Keys: 1, 2, 3,
Values: Java, Python, JavaScript,
Entries: 1=Java, 2=Python, 3=JavaScript,

8. Creating HashMap from Other Maps


In Java, we can also create a hashmap from other maps. For example,

import java.util.HashMap;
import java.util.TreeMap;

class Main {
public static void main(String[] args) {

// create a treemap
TreeMap<String, Integer> evenNumbers = new TreeMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("TreeMap: " + evenNumbers);

// create hashmap from the treemap


HashMap<String, Integer> numbers = new HashMap<>(evenNumbers);
numbers.put("Three", 3);
System.out.println("HashMap: " + numbers);
}
}

Output:
TreeMap: {Four=4, Two=2}
HashMap: {Two=2, Three=3, Four=4}

9. Java Map Example: comparingByKey()


import java.util.*;
class MapExample3{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey())
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}

Output:
100=Amit
101=Vijay
102=Rahul

10. Java Map Example: comparingByKey() in Descending Order


import java.util.*;
class MapExample4{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}

Output:
102=Rahul
101=Vijay
100=Amit

11. Java Map Example: comparingByValue()


import java.util.*;
class MapExample5{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByValue())
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}

Output:
100=Amit
102=Rahul
101=Vijay
12. Java Map Example: comparingByValue() in Descending Order
import java.util.*;
class MapExample6{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}

Output:
101=Vijay
102=Rahul
100=Amit
13. Synchronized HashMap
Using Collections.synchronizedMap() method.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JavaHashMapPrograms


{
public static void main(String[] args)
{
//Creating the HashMap

HashMap<String, Integer> map = new HashMap<String, Integer>();

//Getting synchronized Map

Map<String, Integer> syncMap = Collections.synchronizedMap(map);


}
}

You might also like