栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA8独有的map遍历方式(非常好用)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA8独有的map遍历方式(非常好用)

使用JAV8 带来的map遍历方式使遍历非常简单

public class LambdaMap {

  private Map map = new HashMap<>();

  @Before
  public void initData() {
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");
    map.put("key4", 4);
    map.put("key5", 5);
    map.put("key5", 'h');
  }


  
  @Test
  public void testErgodicWayOne() {
    System.out.println("---------------------Before JAVA8 ------------------------------");
    for (String key : map.keySet()) {
      System.out.println("map.get(" + key + ") = " + map.get(key));
    }
    System.out.println("---------------------JAVA8 ------------------------------");
    map.keySet().forEach(key -> System.out.println("map.get(" + key + ") = " + map.get(key)));
  }

  
  @Test
  public void testErgodicWayTwo() {
    System.out.println("---------------------Before JAVA8 ------------------------------");
    Iterator> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
      Map.Entry entry = iterator.next();
      System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue());
    }
    System.out.println("---------------------JAVA8 ------------------------------");
    map.entrySet().iterator().forEachRemaining(item -> System.out.println("key:value=" + item.getKey() + ":" + item.getValue()));
  }

  
  @Test
  public void testErgodicWayThree() {
    System.out.println("---------------------Before JAVA8 ------------------------------");
    for (Map.Entry entry : map.entrySet()) {
      System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue());
    }
    System.out.println("---------------------JAVA8 ------------------------------");
    map.entrySet().forEach(entry -> System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue()));
  }

  
  @Test
  public void testErgodicWayFour() {
    System.out.println("---------------------Before JAVA8 ------------------------------");
    for (Object value : map.values()) {
      System.out.println("map.value = " + value);
    }
    System.out.println("---------------------JAVA8 ------------------------------");
    map.values().forEach(System.out::println); // 等价于map.values().forEach(value -> System.out.println(value));
  }

  
  @Test
  public void testErgodicWayFive() {
    System.out.println("---------------------only JAVA8 ------------------------------");
    map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135751.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号