Java8中Map的遍历方式总结

Java8中Map的遍历方式总结

  • 一、需求
  • 二、代码展示
  • 三、运行结果
  • 四、参考资料

一、需求

使用Java8进行map遍历与不使用java8进行map遍历的比较

二、代码展示

本人使用的maven工程,具体依赖包可参考import内容

package com.tinet.a_javase;

import com.google.common.collect.Maps;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * Java8中Map的遍历方式总结
 *
 * @author
 * @version 1.0
 * @date 2021/1/13 21:14
 */
public class MapTest {
  private Map<String, Object> map = Maps.newHashMap();

  @BeforeEach
  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');
  }
  /**
   * 遍历Map的方式一
   * 通过Map.keySet遍历key和value
   */
  @Test
  public void test01(){
    System.out.println("Before Java8");
    for (String key : map.keySet()) {
      System.out.println(key + "->" + map.get(key));
    }
    System.out.println("Java 8");
    map.keySet().forEach(key -> System.out.println(key + "->" + map.get(key)));
  }
  /**
   * 遍历Map第二种
   * 通过Map.entrySet使用Iterator遍历key和value
   */
  @Test
  public void test02(){
    System.out.println("Before Java8");
    Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()){
      Entry<String, Object> entry = iterator.next();
      System.out.println(entry.getKey() + "->" + entry.getValue());
    }
    System.out.println("Java 8");
    map.entrySet().iterator().forEachRemaining(stringObjectEntry -> System.out.println(stringObjectEntry.getKey() + "->" + stringObjectEntry.getValue()));
  }
  /**
   * 遍历Map第三种
   * 通过Map.entrySet遍历key和value,在大容量时推荐使用
   */
  @Test
  public void test03(){
    System.out.println("Before Java8");
    for (Entry<String, Object> entry : map.entrySet()) {
      System.out.println(entry.getKey() + "->" + entry.getValue());
    }
    System.out.println("Java 8");
    map.entrySet().forEach(stringObjectEntry -> System.out.println(stringObjectEntry.getKey() + "->" + stringObjectEntry.getValue()));
  }
  /**
   * 遍历Map第四种
   * 通过Map.values()遍历所有的value,但不能遍历key
   */
  @Test
  public void test04(){
    System.out.println("Before Java8");
    for (Object value : map.values()) {
      System.out.println("map.value = " + value);
    }
    System.out.println("Java 8");
    map.values().forEach(System.out::println);
//    map.values().forEach(value -> System.out.println("map.value = " + value));
  }
  /**
   * 遍历Map第五种
   * 通过k,v遍历,Java8独有的
   */
  @Test
  public void test05(){
    System.out.println("only Java 8");
    map.forEach((k,v) -> System.out.println(k + "->" + v));
  }

}

三、运行结果

Java8中Map的遍历方式总结_第1张图片

四、参考资料

1、Java8中Map的遍历方式总结
2、关于Java中的Map遍历方式比较

你可能感兴趣的:(java,8,新特性,java,hashmap)