通过Map.values()遍历所有的value,不能遍历key public class TestDemo{ public static void main(String[] args) { HashMap<String,String> hashMap = new HashMap<>(); hashMap.put("name","Jack"); hashMap.put("sex","boy"); // 通过Map.values()遍历所有的value,不能遍历key for (String v : hashMap.values()) { System.out.println("value=https://www.isolves.com/it/cxkf/sf/2020-03-08/" + v); } } }
执行结果如下:
【Java HashMap遍历的四种方式】 value=https://www.isolves.com/it/cxkf/sf/2020-03-08/boy value=Jack
通过获取HashMap中所有的key按照key来遍历 public class TestDemo{ public static void main(String[] args) { HashMap<String,String> hashMap = new HashMap<>(); hashMap.put("name","Jack"); hashMap.put("sex","boy"); // 通过获取HashMap中所有的key按照key来遍历 for (String key : hashMap.keySet()) { //得到每个key多对用value的值 String value = https://www.isolves.com/it/cxkf/sf/2020-03-08/hashMap.get(key); System.out.println("key="+ key +"; value="+value); } } }
执行结果如下:
key=sex; value=https://www.isolves.com/it/cxkf/sf/2020-03-08/boy key=name; value=Jack
通过Map.entrySet使用iterator遍历key和value public class TestDemo{ public static void main(String[] args) { HashMap<String,String> hashMap = new HashMap<>(); hashMap.put("name","Jack"); hashMap.put("sex","boy"); // 通过Map.entrySet使用iterator遍历key和value Iterator<Map.Entry<String, String>> entryIterator = hashMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<String, String> entry = entryIterator.next(); System.out.println("key=" + entry.getKey() + "; value= https://www.isolves.com/it/cxkf/sf/2020-03-08/" + entry.getValue()); } } }
执行结果如下:
key=sex; value=https://www.isolves.com/it/cxkf/sf/2020-03-08/boy key=name; value=Jack
通过Map.entrySet遍历key和value public class TestDemo{ public static void main(String[] args) { HashMap<String,String> hashMap = new HashMap<>(); hashMap.put("name","Jack"); hashMap.put("sex","boy"); // 通过Map.entrySet遍历key和value,[推荐] for (Map.Entry<String, String> stringEntry : hashMap.entrySet()){ System.out.println("key=" + stringEntry.getKey() + "; value=https://www.isolves.com/it/cxkf/sf/2020-03-08/" + stringEntry.getValue()); } } }
执行结果如下:
key=sex; value=https://www.isolves.com/it/cxkf/sf/2020-03-08/boy key=name; value=Jack
推荐阅读
- 5种创建Java对象的方式
- Java中数据传输加密与签名那些事
- Java随机产生中文昵称
- JDBC基础整理
- JavaScript 数据类型与类型判断详解
- 图解Java内存区域
- Java虚拟机工作原理详解
- 12个提高 JavaScript 技能的概念
- Java 实现6种负载均衡算法
- 四个最佳实践,引导你写出高质量JavaScript模块