C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: We create a HashMap with String keys and Integer values. When we use a diamond, the type arguments are automatically chosen.
Step 2: The put method receives 2 arguments: the key we are trying to add, and the value linked to that key.
Step 3: We call the get() method. This looks into the HashSet and, if found, returns the value for the key.
Step 4: We display the values returned by get(). For "dog" we have 1, and for "cat" we have 2.
Java program that uses HashMap
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Step 1: create new HashMap.
// ... Uses diamond inference on right side.
HashMap<String, Integer> hash = new HashMap<>();
// Step 2: put 3 keys with values.
hash.put("dog", 1);
hash.put("cat", 2);
hash.put("rabbit", 3);
// Step 3: look up some known values.
int a = hash.get("dog");
int b = hash.get("cat");
// Step 4: display results.
System.out.println("DOG: " + a);
System.out.println("CAT: " + b);
}
}
Output
DOG: 1
CAT: 2
Tip: It is also possible to loop over the entries in the HashMap. This can eliminate the need for a value lookup in the for-loop.
ForJava program that loops over keys
import java.util.HashMap;
import java.util.Set;
public class Program {
public static void main(String[] args) {
// Create HashMap of three entries.
HashMap<String, Integer> h = new HashMap<>();
h.put("apple", 1);
h.put("peach", 2);
h.put("guava", 3);
// Get keys.
Set<String> keys = h.keySet();
// Loop over String keys.
for (String key : keys) {
System.out.println(key);
}
}
}
Output
guava
apple
peach
Entry: We must specify an Entry with the key and value types of the HashMap. We then can call getKey and getValue.
Ordering: The HashMap does not remember the order we add items to it. To maintain ordering, please consider a LinkedHashMap.
LinkedHashMapJava program that loops over HashMap, entrySet
import java.util.HashMap;
import java.util.Map.Entry;
public class Program {
public static void main(String[] args) {
// Create HashMap and put 3 entries in it.
HashMap<String, Integer> values = new HashMap<>();
values.put("Java", 6);
values.put("Python", 4);
values.put("C#", 5);
// Loop over HashMap with entrySet.
// ... The ordering is not maintained.
for (Entry<String, Integer> pair : values.entrySet()) {
System.out.println(pair.getKey() + "::" + pair.getValue());
}
}
}
Output
C#::5
Java::6
Python::4
True: It returns true if the key is found, and false otherwise. We often test it in an if-statement.
IfTip: The containsKey method is fast because a hash code is used to locate the key. Using containsValue() is slower—no hash is available.
Java program that uses containsKey
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Create an Integer HashMap.
HashMap<Integer, Integer> h = new HashMap<>();
h.put(1, 1000);
h.put(20, 1001);
h.put(300, 1003);
// Use containsKey.
if (h.containsKey(1)) {
System.out.println("1 was found");
}
if (h.containsKey(300)) {
System.out.println("300 was found");
}
if (!h.containsKey(400)) {
System.out.println("400 was not found");
}
}
}
Output
1 was found
300 was found
400 was not found
Java program that uses containsValue
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Create a HashMap of fruit and their color.
HashMap<String, String> fruit = new HashMap<>();
fruit.put("apple", "red");
fruit.put("orange", "orange");
fruit.put("banana", "yellow");
fruit.put("raspberry", "red");
// See if there is a red value.
if (fruit.containsValue("red")) {
System.out.println("Red fruit detected!");
// Loop over all keys and print them if they have "red" values.
for (String key : fruit.keySet()) {
if (fruit.get(key) == "red") {
System.out.println(key);
}
}
}
}
}
Output
Red fruit detected!
raspberry
apple
Java program that uses size
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// ... Create empty HashMap.
HashMap<Integer, Integer> map = new HashMap<>();
System.out.println(map.size());
// ... Add one entry.
map.put(1, 100);
System.out.println(map.size());
// Add two more entries.
map.put(2, 200);
map.put(3, 300);
System.out.println(map.size());
}
}
Output
0
1
3
Boolean: IsEmpty returns a Boolean. It is often used within if-statements, but the Boolean can be used in any way.
Java program that uses isEmpty
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
HashMap<String, Boolean> map = new HashMap<>();
// The HashMap is currently empty.
if (map.isEmpty()) {
System.out.println("It is empty");
}
map.put("cat", true);
map.put("dog", false);
// IsEmpty now returns false.
System.out.println(map.isEmpty());
}
}
Output
It is empty
false
Note: We then loop over the HashMap. We use a foreach-loop. Each element is of String type.
Java program that uses values
import java.util.Collection;
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
HashMap<String, String> hash = new HashMap<>();
hash.put("cat", "black");
hash.put("dog", "brown");
hash.put("bird", "blue");
// Get all values from the HashMap.
Collection<String> values = hash.values();
for (String value : values) {
System.out.println(value);
}
}
}
Output
blue
black
brown
Java program that uses getOrDefault
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Create HashMap and put one key.
HashMap<Integer, Integer> hash = new HashMap<>();
hash.put(0, 10);
// Get keys 0 and 1, returning -1 if nothing there.
int result = hash.getOrDefault(0, -1); // Exists
int result2 = hash.getOrDefault(1, -1); // Does not exist
System.out.println(result);
System.out.println(result2);
}
}
Output
10
-1
Tip: We can use putIfAbsent repeatedly if only the first encountered key needs to be retained.
Java program that uses putIfAbsent
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Create HashMap and use putIfAbsent.
HashMap<String, Double> hash = new HashMap<>();
hash.putIfAbsent("cat", 1.5);
hash.putIfAbsent("cat", 2.0);
// ... This returns the first value added.
double value = hash.get("cat");
System.out.println(value);
}
}
Output
1.5
Collections.sort: We sort the ArrayList containing the keys with this method. The keys are now in ascending order.
SortJava program that sorts HashMap
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
public class Program {
public static void main(String[] args) {
HashMap<String, String> hash = new HashMap<>();
hash.put("red", "color");
hash.put("tomato", "fruit");
hash.put("pizza", "lunch");
// Put keys into an ArrayList and sort it.
Set<String> set = hash.keySet();
ArrayList<String> list = new ArrayList<String>();
list.addAll(set);
Collections.sort(list);
// Display sorted keys and their values.
for (String key : list) {
System.out.println(key + ": " + hash.get(key));
}
}
}
Output
pizza: lunch
red: color
tomato: fruit
Comparator: We implement a Comparator class called EntryComparator. In compare() it calls compareTo on the Entry's values.
ArrayList: In main, we copy the EntrySet to an ArrayList which can be sorted. We call addAll to add the Entries.
Sort: In ArrayList sort(), we pass our EntryComparer. This sorts the ArrayList of Entries by each Entry's value.
Java program that sorts EntrySets
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
class EntryComparator implements Comparator<Entry<String, Integer>> {
public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
// Compare the values.
return arg0.getValue().compareTo(arg1.getValue());
}
}
public class Program {
public static void main(String[] args) {
// Create HashMap and add four pairs to it.
HashMap<String, Integer> hash = new HashMap<>();
hash.put("bird ", 500);
hash.put("zebra", 2);
hash.put("cat ", 10);
hash.put("dog ", 5);
// Copy keySet into ArrayList.
// ... Sort with EntryComparator.
ArrayList<Entry<String, Integer>> copy = new ArrayList<>();
copy.addAll(hash.entrySet());
copy.sort(new EntryComparator());
// Display.
for (Entry<String, Integer> e : copy) {
System.out.println(e.getKey() + "..." + e.getValue());
}
}
}
Output
zebra...2
dog ...5
cat ...10
bird ...500
Java program that uses static HashMap
import java.util.HashMap;
public class Program {
static HashMap<String, String> map = new HashMap<>();
public static void main(String[] args) {
// Use static HashMap in static methods.
addAnimals();
testAnimals();
}
static void addAnimals() {
map.putIfAbsent("cat", "black");
map.putIfAbsent("bird", "blue");
}
static void testAnimals() {
System.out.println(map.getOrDefault("cat", "missing"));
System.out.println(map.getOrDefault("?", "missing"));
}
}
Output
black
missing
Version 1: In this version of the code, we search a HashMap for one key. We call containsKey() on the HashMap.
Version 2: Here we search an ArrayList. We call the contains() method on the ArrayList instance.
Result: The HashMap delivers a stunning performance boost. It returns the correct result over 2 times faster than the ArrayList.
Tip: Even for small collection lookups, where only three elements exist, a HashMap locates an element faster. HashMap is a clear win.
Java program that times HashMap, ArrayList
import java.util.HashMap;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) throws Exception {
HashMap<Integer, Boolean> hash = new HashMap<>();
hash.put(100, true);
hash.put(1000, true);
hash.put(50, true);
ArrayList<Integer> array = new ArrayList<>();
array.add(100);
array.add(1000);
array.add(50);
long t1 = System.currentTimeMillis();
// Version 1: do HashMap lookups.
for (int i = 0; i < 10000000; i++) {
if (!hash.containsKey(50)) {
throw new Exception();
}
}
long t2 = System.currentTimeMillis();
// Version 2: do ArrayList lookups.
for (int i = 0; i < 10000000; i++) {
if (!array.contains(50)) {
throw new Exception();
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
91 ms, HashMap: containsKey
244 ms, ArrayList: contains