search
HomeJavajavaTutorialDetailed explanation and example code of java HashMap

java HashMap

/*
* Map集合的特点
* 将键映射值的对象,一个映射不能包含重复的值;每个键最多只能映射到一个值
* 
* Map集合和Collection集合的区别?
* Map集合存储元素是成对出现的,Map集合的键是唯一的,就是可重复的。可以把这个理解为:夫妻对
* Collection集合存储元素是单独出现的,Collection的儿子Set是唯一的,List是可重复的,可以把这个理解为:光棍
* 
* 注意:
* Map集合的数据结构值针对键有效,限值无效
* Collection集合的数据结构是针对元素有效
* 
* Map集合的功能概述:
* 1:添加功能
* V put(K key,V value);//添加元素
* 如果键是第一次存储,就直接存储元素,返回null
* 如果键不是第一次存储,就用值把以前的值替换掉,返回以前的值
* 
* 2:删除功能
* void clear();//移除所有的键值对元素
* V remove(Object key);//根据键删除键值对元素,并把值返回
* 
* 3:判断功能
* boolean containsKey(Object key);//判断集合是否包含指定的键
* boolean containsValue(Object value);//判断集合是否包含指定的值
* boolean isEmpty();//判断集合是否为空
* 
* 4:获取功能
* set<Map,Entry<E,V>> entrySet();获取键值对的对象集合
* V get(Object key);//根据键获取值
* Set<K> keySet();//获取集合中所有键的集合
* Collection<V> values();//获取集合中所有值的集合
* 
* 5:长度功能
* int size();//返回集合中的键值对的对数
* */

Traversal of Map collection

Method 1, query value based on key

Get the collection of all keys

Traverse the collection of keys , get each key

Query the value based on the key

Method 2, query the key and value based on the key-value pair object

Get the collection of all key-value pair objects

Traverse the collection of key-value pair objects and obtain the object of each key-value pair

Query the key and value based on the key-value pair object

Method 1, Query the value based on the key

/*
 
* Map集合的遍历,根据键查询值
* 
* 思路:
* A:获取所有的键
* B:遍历键的集合,获取得到每一个键
* C:根据键查询值
* */
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
  
/*
 * Map集合的遍历,根据键查询值
 *
 * 思路:
 * A:获取所有的键
 * B:遍历键的集合,获取得到每一个键
 * C:根据键查询值
 * */
  
public class IntegerDemo {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
  
    Map<String, String> map = new HashMap<String, String>();
  
    map.put("hello", "world");
    map.put("java", "c++");
    map.put("sql", "os");
  
    System.out.println(map);
  
    // A:获取所有的键
    Set<String> set = map.keySet();
  
    // B:遍历键的集合,获取得到每一个键
    for (String key : set) {
      // C:根据键查询值
      String value = map.get(key);
      System.out.println(key + "---" + value);
    }
  }
}

Method 2, query the key and value based on the object of the key-value pair

/*
* Map集合的遍历,根据对象查询键和值
*
* 思路:
* A:获取所有的键值对对象的集合
* B:遍历键值对对象的集合,得到每一个键值对的对象
* C:获取键和值
* */
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
  
/*
 * Map集合的遍历,根据对象查询键和值
 *
 * 思路:
 * A:获取所有的键值对对象的集合
 * B:遍历键值对对象的集合,得到每一个键值对的对象
 * C:获取键和值
 * */
  
public class IntegerDemo {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
  
    Map<String, String> map = new HashMap<String, String>();
  
    map.put("hello", "world");
    map.put("java", "c++");
    map.put("sql", "os");
  
    System.out.println(map);
  
    // A:获取所有的键值对对象的集合
    Set<Map.Entry<String, String>> set = map.entrySet();
  
    // B:遍历键值对对象的集合,得到每一个键值对的对象
    for (Map.Entry<String, String> me : set) {
      // C:获取键和值
      String key = me.getKey();
      String value = me.getValue();
      System.out.println(key + "---" + value);
    }
  }
}

/*
* 1:HashMap和Hashtable的区别?
* HashMap线程不安全,效率高,允许null键和null值
* Hashtable线程安全,效率低,不允许null键和null值
*
* 2:List,Set,Map等接口是否都继承于Map接口?
* List,Set不是继承自Map接口,它们继承自Collection接口
* Map接口本身就是一个顶层接口
* */
import java.util.HashMap;
import java.util.Hashtable;
  
public class IntegerDemo {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
  
    HashMap<String, String> hm = new HashMap<String, String>();
    Hashtable<String, String> ht = new Hashtable<String, String>();
  
    hm.put("hello", "world");
    hm.put("java", "c++");
    hm.put(null, "sql");
  
    ht.put("hello", "world");
    ht.put("java", "c++");
    ht.put(null, "sql");// Exception in thread "main"
              // java.lang.NullPointerException
  }
}

Thanks for reading, I hope this helps everyone, and thank you for your support of this site!

For more java HashMap detailed explanations and example code related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor