HashMap遍历的常用四种方式 ——应用JAVA8新特性Lambda表达式
2019-04-23 10:14
375 查看
前言:本文将为你展示Java中HashMap的四种典型遍历方式。
如果你使用Java8,由于该版本JDK支持lambda表达式,可以采用第4种方式来遍历。
一:通过forEach循环遍历
@Test public void test1() throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(3, "c"); map.put(5, "e"); map.put(2, "b"); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + " Value = "+ entry.getValue()); } }
输出结果:
Key = 1 Value = a
Key = 2 Value = b
Key = 3 Value = c
Key = 5 Value = e
二:通过forEach迭代键值对 如果你只想使用键或者值,推荐使用此方式
@Test public void test2() throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(3, "c"); map.put(5, "e"); map.put(2, "b"); for (Integer key : map.keySet()) { System.out.println("Key = " + key); } for (String value : map.values()) { System.out.println("Value = " + value); } }
输出结果:
Key = 1
Key = 2
Key = 3
Key = 5
Value = a
Value = b
Value = c
Value = e
三:使用迭代器进行遍历
@Test public void test3() throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(3, "c"); map.put(5, "e"); map.put(2, "b"); Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>)iterator.next(); Integer key = entry.getKey(); String value = entry.getValue(); System.out.println("Key = " + key + " Value = "+ value); } }
输出结果:
Key = 1 Value = a
Key = 2 Value = b
Key = 3 Value = c
Key = 5 Value = e
四:强烈推荐通过Java8 Lambda表达式遍历
@Test public void test4() throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(3, "c"); map.put(5, "e"); map.put(2, "b"); map.forEach((key, value) -> { System.out.println("Key = " + key + " " + " Value = " + value); }); }
输出结果:
Key = 1 Value = a
Key = 2 Value = b
Key = 3 Value = c
Key = 5 Value = e
相关文章推荐
- Java中HashMap遍历的四种方式
- java中Map集合的常用遍历方法及HashMap的应用实例
- Java8新特性Lambda表达式的基本使用(常用功能)
- Java中HashMap的四种遍历方式
- java中Map集合的常用遍历方法及HashMap的应用实例
- Java中HashMap遍历的四种方式
- Java -- HashMap的四种遍历方式
- java中Map集合的常用遍历方法及HashMap的应用实例
- Java——HashMap<> 四种遍历方式
- 代码笔记 | java 正则表达式高级篇(四种常用的处理方式:匹配 分割 替代 获取)
- Java中HashMap遍历的四种方式
- java 正则表达式高级篇(四种常用的处理方式:匹配 分割 替代 获取)
- java 正则表达式高级篇(四种常用的处理方式:匹配 分割 替代 获取)
- java中Map集合的常用遍历方法及HashMap的应用实例
- Java8新特性之forEach+Lambda 表达式遍历Map和List
- java8新特性之lambda表达式的应用
- Java中HashMap遍历的四种方式
- java中Map集合的常用遍历方法及HashMap的应用实例
- Java --- HashMap的四种循环遍历方式及性能对比
- Java8新特性之forEach+Lambda 表达式遍历Map和List