Java HashMap is a map interface that allows us to store data by key-value pair where key should be unique.
HashMap Syntax:
HashMap<datatype1, datatype2> obj= new HashMap<datatype1, datatype2>();
Let’s see a simple example of HashMap to store key and value pair.
A simple program:
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> hashmap=new HashMap<Integer,String>();
hashmap.put(1,"America");
hashmap.put(2,"Bangladesh");
hashmap.put(3,"Canada");
hashmap.put(4,"Denmark");
hashmap.put(5,"England");
System.out.println(hashmap.get(2)); //2 is the key
}
}
Output:
Bangladesh
If you want to print all of the stored data, then the program looks like:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> hashmap=new HashMap<Integer,String>();
hashmap.put(1,"America");
hashmap.put(2,"Bangladesh");
hashmap.put(3,"Canada");
hashmap.put(4,"Denmark");
hashmap.put(5,"England");
for(Map.Entry m : hashmap.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
1 America
2 Bangladesh
3 Canada
4 Denmark
5 England
Duplicate Key:
Method: hashmap.put(duplicate_key, newValue);
If you duplicate the key, then first one will be replaced by second one.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> hashmap=new HashMap<Integer,String>();
hashmap.put(1,"America");
hashmap.put(2,"Bangladesh");
hashmap.put(3,"Canada");
hashmap.put(4,"Denmark");
hashmap.put(5,"England");
hashmap.put(1,"Germany");
for(Map.Entry m : hashmap.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
1 Germany
2 Bangladesh
3 Canada
4 Denmark
5 England
Delete Data:
Method: hashmap.remove(key)
If you want to remove a data from HashMap, then the program is:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> hashmap=new HashMap<Integer,String>();
hashmap.put(1,"America");
hashmap.put(2,"Bangladesh");
hashmap.put(3,"Canada");
hashmap.put(4,"Denmark");
hashmap.put(5,"England");
hashmap.remove(5);
for(Map.Entry m : hashmap.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
1 America
2 Bangladesh
3 Canada
4 Denmark
Replace Data:
Method: hashmap.replace(key,newValue);
If you want to replace a value with another value, then the program looks like:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> hashmap=new HashMap<Integer,String>();
hashmap.put(1,"America");
hashmap.put(2,"Bangladesh");
hashmap.put(3,"Canada");
hashmap.put(4,"Denmark");
hashmap.put(5,"England");
hashmap.replace(5,"France");
for(Map.Entry m : hashmap.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
1 America
2 Bangladesh
3 Canada
4 Denmark
5 France
Leave a Reply