HashMap and HashSet
HashMap stores key and value pairs: put, get, containsKey, remove, keySet, values and getOrDefault. HashSet stores unique values. For sorted keys use TreeMap, and for insertion order use LinkedHashMap.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("apple", 5);
stock.put("mango", 12);
stock.put("apple", 7);
System.out.println(stock);
System.out.println(stock.get("mango"));
System.out.println(stock.getOrDefault("kiwi", 0));
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}
Set<Integer> unique = new HashSet<>(List.of(1, 2, 2, 3, 3));
System.out.println(unique.size());
}
}Result
{apple=7, mango=12}
12
0
apple=7
mango=12
3Exercise
Read a value by key.
map.("apple")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.