HashMap
– это объект, который хранит оба ключ = значение
в виде пары. Это HashMap
допускает нулевые значения и нулевой ключ, несинхронизированный и не гарантирующий порядок отображения.
["key","value"] = ["java","mkyong.com"]
1. Базовая хэш-карта
1.1 Добавить элемент
Map map = new HashMap(); map.put("PostgreSQL", "Free Open Source Enterprise Database");
1.2 Получить товар
map.get("PostgreSQL"); // output : Free Open Source Enterprise Database
1.3 Обновление элемента
map.put("PostgreSQL", "Still the best!"); map.get("PostgreSQL"); // output : Still the best! // @Since 1.8 map.replace("PostgreSQL", "Still the best! 2"); map.get("PostgreSQL"); // output : Still the best! 2
1.4 Удалить элемент
map.remove("PostgreSQL"); map.get("PostgreSQL"); // output : null
1.5 Удалить все
map.clear();
1.6 Получить Размер
map.size();
2. Хэш-карта цикла
Существует 3 способа зациклить или повторить хэш-карту
2.1 Если возможно, всегда используйте Java 8 Для каждого
, простой и приятный.
Mapmap = new HashMap<>(); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));
2.2 Нормально для цикла.
Mapmap = new HashMap<>(); for (Map.Entry entry : map.entrySet()) { System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); }
2.3 Итератор, классический.
Mapmap = new HashMap<>(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); }
3. 2.3 Итератор, классический.
3.1 Это HashMap
не синхронизирован, если несколько потоков одновременно обращаются к HashMap
, это приведет к искажению значений. Чтобы использовать HashMap
в среде с несколькими потоками, попробуйте Коллекции.Синхронизированная карта(новая хэш-карта<>())
для создания синхронизированной карты.
package com.mkyong; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class HashMapSynchronized { public static void main(String[] args) { // this map is synchronized Mapmap = Collections.synchronizedMap(new HashMap<>()); map.put("web", 1024); map.put("backend", 2048); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); } }
4. Хэш-карта
Полный пример, просто для справки.
package com.mkyong; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("PostgreSQL", "Free Open Source Enterprise Database"); map.put("DB2", "Enterprise Database , It's expensive"); map.put("Oracle", "Enterprise Database , It's expensive"); map.put("MySQL", "Free Open SourceDatabase (no more, try MariaDB)"); // Get System.out.println(map.get("PostgreSQL")); // Free Open Source Enterprise Database // Update map.put("PostgreSQL", "Still the best!"); System.out.println(map.get("PostgreSQL")); // Still the best! // @Since 1.8 map.replace("PostgreSQL", "Still the best! 2"); System.out.println(map.get("PostgreSQL")); // Still the best! 2 // Remove map.remove("PostgreSQL"); System.out.println(map.get("PostgreSQL")); // null // Size System.out.println(map.size()); // 3 // loop System.out.println("Iterator loop..."); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } System.out.println("for loop..."); for (Map.Entry entry : map.entrySet()) { System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } // Java 8 System.out.println("forEach loop..."); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); // clear everything map.clear(); // nothing map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); } }
Выход
Free Open Source Enterprise Database Still the best! Still the best! 2 null 3 Iterator loop... [Key] : DB2 [Value] : Enterprise Database , It's expensive [Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB) [Key] : Oracle [Value] : Enterprise Database , It's expensive for loop... [Key] : DB2 [Value] : Enterprise Database , It's expensive [Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB) [Key] : Oracle [Value] : Enterprise Database , It's expensive forEach loop... [Key] : DB2 [Value] : Enterprise Database , It's expensive [Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB) [Key] : Oracle [Value] : Enterprise Database , It's expensive
Рекомендации
Оригинал: “https://mkyong.com/java/how-to-use-hashmap-tutorial-java/”