GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing zetcode.com — Java HashMap - learn how to use Java HashMap Java HashMaplast modified February 21, 2024 In this article we show how to use Java HashMap collection.
HashMap is a container that stores key-value pairs. Each key is
associated with one value. Keys in a
Map.Entry represents a key-value pair in
HashMap Constructors
HashMap methods
The following table provides a few
In this article we work with several of these methods. HashMap creation
Map<String, String> capitals = new HashMap<>(); We specify the types of keys and values between angle brackets. Thanks to type inference, it is not necessary to provide types on the right side of the declaration. The put method
The capitals.put("svk", "Bratislava");
The first parameter is the key, the second is the value. The remove method
The capitals.remove("pol");
The parameter is the key whose mapping is to be removed from the map. HashMap initialization
Since Java 9, we have factory methods for Main.java
import java.util.Map;
import static java.util.Map.entry;
void main() {
Map<Integer, String> colours = Map.of(1, "red", 2, "blue", 3, "brown");
System.out.println(colours);
Map<String, String> countries = Map.ofEntries(
entry("de", "Germany"),
entry("sk", "Slovakia"),
entry("ru", "Russia"));
System.out.println(countries);
}
The example uses Main.java
import java.util.HashMap;
import java.util.Map;
// up to Java 8
void main() {
Map<String, String> countries = new HashMap<>() {
{
put("de", "Germany");
put("sk", "Slovakia");
put("ru", "Russia");
}
};
System.out.println(countries);
}
In this example we create a modifiable hashmap. This way of initialization is dubbed double-braced hashmap initialization. The size method
The size of the Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
int size = capitals.size();
System.out.printf("The size of the HashMap is %d%n", size);
capitals.remove("pol");
capitals.remove("ita");
size = capitals.size();
System.out.printf("The size of the HashMap is %d%n", size);
}
In the code example, we create a capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
With int size = capitals.size(); Here we get the size of the map. capitals.remove("pol");
capitals.remove("ita");
With The size of the HashMap is 6 The size of the HashMap is 4 The get method
To retrieve a value from a Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
String cap1 = capitals.get("ita");
String cap2 = capitals.get("svk");
System.out.println(cap1);
System.out.println(cap2);
}
In the example, we retrieve two values from the map. String cap2 = capitals.get("svk");
Here we get a value which has The clear method
The Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
capitals.clear();
if (capitals.isEmpty()) {
System.out.println("The map is empty");
} else {
System.out.println("The map is not empty");
}
}
In the example, we remove all elements and print the size of the map to the console. capitals.clear();
We remove all pairs with if (capitals.isEmpty()) {
System.out.println("The map is empty");
} else {
System.out.println("The map is not empty");
}
With the The containsKey method
The Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
String key1 = "ger";
String key2 = "rus";
if (capitals.containsKey(key1)) {
System.out.printf("HashMap contains %s key%n", key1);
} else {
System.out.printf("HashMap does not contain %s key%n", key1);
}
if (capitals.containsKey(key2)) {
System.out.printf("HashMap contains %s key%n", key2);
} else {
System.out.printf("HashMap does not contain %s key%n", key2);
}
}
In the example, we check if the map contains two keys. if (capitals.containsKey(key1)) {
System.out.printf("HashMap contains %s key%n", key1);
} else {
System.out.printf("HashMap does not contain %s key%n", key1);
}
This if statement prints a message depending on whether the map contains the given key. HashMap contains ger key HashMap does not contain rus key The replace method
There are replace(K key, V value) This method replaces the entry for the specified key only if it is currently mapped to some value. replace(K key, V oldValue, V newValue) This method replaces the entry for the specified key only if it is currently mapped to the specified value. Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("day", "Monday");
capitals.put("country", "Poland");
capitals.put("colour", "blue");
capitals.replace("day", "Sunday");
capitals.replace("country", "Russia", "Great Britain");
capitals.replace("colour", "blue", "green");
capitals.entrySet().forEach(System.out::println);
}
In the example, we replace pairs in the map with capitals.replace("day", "Sunday");
Here we replace a value for the capitals.replace("country", "Russia", "Great Britain");
In this case, the value is not replaced because the key
is not currently set to capitals.replace("colour", "blue", "green");
Because the old value is correct, the value is replaced. country=Poland colour=green day=Sunday Convert HashMap to List
In the next example we convert Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
void main() {
Map<String, String> colours = Map.of(
"AliceBlue", "#f0f8ff",
"GreenYellow", "#adff2f",
"IndianRed", "#cd5c5c",
"khaki", "#f0e68c"
);
Set<Map.Entry<String, String>> entries = colours.entrySet();
List<Map.Entry<String, String>> mylist = new ArrayList<>(entries);
System.out.println(mylist);
}
The Iteration with forEach
We use the Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
capitals.forEach((k, v) -> System.out.format("%s: %s%n", k, v));
}
In the code example, we iterate over a capitals.forEach((k, v) -> System.out.format("%s: %s%n", k, v));
With Iteration with enhanced for loop
The enhanced for loop can be used to iterate over a Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
for (Map.Entry<String, String> pair: capitals.entrySet()) {
System.out.format("%s: %s%n", pair.getKey(), pair.getValue());
}
}
In the example we iterate over a for (Map.Entry<String, String> pair: capitals.entrySet()) {
System.out.format("%s: %s%n", pair.getKey(), pair.getValue());
}
In each for cycle, a new key-value couple is assigned to the With type inference, we can shorten the code a bit. Main.java
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
for (var pair: capitals.entrySet()) {
System.out.format("%s: %s%n", pair.getKey(), pair.getValue());
}
}
We shorten the code by using a Iteration over keys
We might want to iterate only over keys of a Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
Set<String> keys = capitals.keySet();
keys.forEach(System.out::println);
}
The example iterates over keys of the Set<String> keys = capitals.keySet();
The keys of a keys.forEach(System.out::println);
We go over the set of keys with Iteration over values
We might want to iterate only over values of a Main.java
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
Collection<String> vals = capitals.values();
vals.forEach(System.out::println);
}
The example iterates over values of a Collection<String> vals = capitals.values();
The values of a vals.forEach(System.out::println);
We go over the collection with Filtering HashMap
Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("hun", "Budapest");
capitals.put("czk", "Prague");
capitals.put("pol", "Warsaw");
capitals.put("ita", "Rome");
Map<String, String> filteredCapitals = capitals.entrySet().stream()
.filter(e -> e.getValue().length() == 6)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
filteredCapitals.entrySet().forEach(System.out::println);
}
In the example, we filter the map to contain only pairs whose values' size is equal to six. czk=Prague ger=Berlin pol=Warsaw List of mapsIn the next example, we have a list of maps. Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
void main() {
Map<String,Integer> fruits1 = new HashMap<>();
fruits1.put("oranges", 2);
fruits1.put("bananas", 3);
Map<String,Integer> fruits2 = new HashMap<>();
fruits2.put("plums", 6);
fruits2.put("apples", 7);
List<Map<String,Integer>> all = new ArrayList<>();
all.add(fruits1);
all.add(fruits2);
all.forEach(e -> e.forEach((k, v) -> System.out.printf("k: %s v %d%n", k, v)));
}
We define two maps and insert them into a list. Then we interate over the list
with two k: oranges v 2 k: bananas v 3 k: plums v 6 k: apples v 7 SourceJava HashMap - language reference
In this article we have presented the Java AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. | ||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |