HashMap
Wed, Jun 17, 2020
4-minute read
Creating a HashMap and Adding key-value pairs to it
import java.util.HashMap;
import java.util.Map;
public class CreateHashMap {
public static void main(String[] args) { // creating a HashMap
Map<String, Integer>numMap = new HashMap<>();
// adding key-value pairs to a HashMap
numMap.put("one", 1);
numMap.put("two", 2);
numMap.put("three", 3);
// adding new key-value pairs to a HashMap
numMap.putIfAbsent("four", 4);
}
}
Accessing keys and modifying their value in HashMap
how to check if a HashMap is empty
how to check a HashMap's size
how to check if a key/value exist
how to modity the value
import java.util.HashMap;
import java.util.Map;
public class KeyHashMap {
public static void main(String[] args) {
// creating a HashMap
Map<String, Integer>checkMap = new HashMap<>();
// check if a hashmap is empty
System.out.println("is empty?: " + checkMap.isEmpty());
// find the size of a hashmap
checkMap.put("xxx", "yyy");
checkMap.put("xxx1", "yyy1");
checkMap.put("xxx2", "yyy2");
System.out.println("is empty?: " + checkMap.size());
//check if the key exists in the HashMap
String username = "xxx";
if(checkMap.containsKey(username)) {
String useradd = checkMap.get(username);
System.out.println(username + useradd);
} else {
System.out.println("not found: " + username);
}
//check if the value exists in the HashMap
if(checkMap.containsValue("yyy")) {
System.out.println("ff");
} else {
System.out.println("xx");
}
numMap.put("one", 1);
numMap.put("two", 2);
numMap.put("three", 3);
// adding new key-value pairs to a HashMap
numMap.putIfAbsent("four", 4);
// modify the value assigned to an existing key
checkMap.put(username, "yyy");
}
}
removing keys from a hashmap
- remove a key from a hashMap
- remove a key from a hashmap only if is associated with a given value
import java.util.HashMap;
import java.util.Map;
public class removeHashMap {
public static void main(String[] args) {
// creating a HashMap
Map<String, Integer>remMap = new HashMap<>();
remMap.put("one", 1);
remMap.put("two", 2);
remMap.put("three", 3);
String rev= "one";
String rem = remMap.remove(rev);
System.out.println("new " + remMap);
//output:
//{two=2, three=3}
boolean isRemoved = remMap.remove("one",1);
System.out.println(isRemoved);
//one, 1 not in a pair anymore, so the output is false;
Obtaining the entrySet, KeySet, values from a HashMap
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Collection;
public class EntryKeyMap {
public static void main(String[] args) {
// creating a HashMap
Map<String, String> enkMap = new HashMap<>();
enkMap.put("one", "1");
enkMap.put("two", "2");
enkMap.put("three", "3");
// HashMap's entry set
Set<Map.Entry<String, String>> enkEntries = enkMap.entrySet();
System.out.println(enkEntries);
// print hashmap in { xxx=yyy, xxx1=yyy1};
// print entrySet is[xxx=yyy, xxx1=yyy1];
// hashmap's key set
Set<String> xname = enkMap.keySet();
System.out.println(xname);
//output:
//[one, two]
// hashmap's value
Collection<String> yname = enkMap.values();
System.out.println(yname);
//output:
//[yyy, yyy1]
```
`Iterating over a hashmap`
```java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class IterateOverHashMap {
public static void main(String[] args) {
Map<String, Double> employeeSalary = new HashMap<>();
employeeSalary.put("David", 76000.00);
employeeSalary.put("John", 120000.00);
employeeSalary.put("Mark", 95000.00);
employeeSalary.put("Steven", 134000.00);
//Iterating over a HashMap using Java 8 forEach and lambda ==="
employeeSalary.forEach((employee, salary) -> {
System.out.println(employee + " => " + salary);
});
// Iterating over the HashMap's entrySet using iterator() ===");
Set<Map.Entry<String, Double>> employeeSalaryEntries = employeeSalary.entrySet();
Iterator<Map.Entry<String, Double>> employeeSalaryIterator = employeeSalaryEntries.iterator();
while (employeeSalaryIterator.hasNext()) {
Map.Entry<String, Double> entry = employeeSalaryIterator.next();
System.out.println(entry.getKey() + " => " + entry.getValue());
}
//Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===");
employeeSalary.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + " => " + entry.getValue());
});
// Iterating over the HashMap's entrySet using simple for-each loop ===");
for(Map.Entry<String, Double> entry: employeeSalary.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
// Iterating over the HashMap's keySet ===");
employeeSalary.keySet().forEach(employee -> {
System.out.println(employee + " => " + employeeSalary.get(employee));
});
}
}
`user defined objects`
```java
import java.util.HashMap;
import java.util.Map;
class Employee {
private Integer id;
private String name;
private String city;
public Employee(Integer id, String name, String city) {
this.id = id;
this.name = name;
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", city='" + city + '\'' +
'}';
}
}
public class HashMapUserDefinedObjectExample {
public static void main(String[] args) {
Map<Integer, Employee> employeesMap = new HashMap<>();
employeesMap.put(1001, new Employee(1001, "Rajeev", "Bengaluru"));
employeesMap.put(1002, new Employee(1002, "David", "New York"));
employeesMap.put(1003, new Employee(1003, "Jack", "Paris"));
System.out.println(employeesMap);
}
{1001=Employee{name='Rajeev', city='Bengaluru'}, 1002=Employee{name='David', city='New York'}, 1003=Employee{name='Jack', city='Paris'}}
Synchronizing Access to Java HashMap
Example demonstrating how to synchronize concurrent modifications to a HashMap
check more information: