Java HashMap遍历的四种方式

通过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



    推荐阅读