遍历HashMap_lambda

HashMap遍历主要有四类方法:

  • 迭代器方式遍历

  • For Each方式遍历

  • Lambda表达式遍历

  • Streams API遍历

其中迭代器、For Each、Streams API又有不同的实现(EntrySet和KeySet),所以有四类七种方式实现

1、迭代器EntrySet方式遍历

public class HashMapDemo{
  public static void main(String[] args){
        Map<Integer,String> map = new HashMap;
        map.put(1,"java");
        map.put(2,"python");
        map.put(3,"C");
        map.put(4,"PHP");
        //1、迭代器EntrySet
        iteratorEntrySet(map);
        //2、迭代器KeySet
        iteratorKeySet(map);
        //3、forEach EntrySet
        forEachEntrySet(map);
        //4、forEach KeySet
        forEachKeySet(map);
        //5、Lambda表达式遍历
        lambdaforMap(map);
        //6、Streams API 单线程方式
        streamsApiOne(map);
        //7、Streams API 多线程
        streamsApiMore(map);
    }
    
    //迭代器EntrySet
    public void iteratorEntrySet(Map<Integer,String> map){
        Iterator<Map.Entry<Integer,String>> iterator = map.entrySet().iterator();
        while (iterator.hashNext()) {
            Map.Entry<Integer,String> entry = iterator.next();
            System.out.println(entry.getKey() + "=====" + entry.getValue());
        }
    }
}

2、迭代器KeySet方式遍历

public void iteratorKeySet(Map<Integer,String> map){
    Iterator<Integer> iterator = map.keySet().iterator();
    while (iterator.hashNext()) {
        Integer key = iterator.next();
        System.out.println(key + "=====" + map.get(key))
    }
}

3、ForEach EntrySet方式遍历

public void forEachEntrySet(Map<Integer,String> map) {
    for(Map.Entry<Integer,String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=====" + entry.getValue());
    }
}

4、ForEach KeySet方式遍历

public void forEachKeySet(Map<Integer,String> map) {
    for (Integer key : map.keySet()) {
        System.out.println(key + "===" + map.get(key));
    }
}

5、Lambda表达式遍历

public void lambdaforMap(Map<Integer,String> map) {
    map.forEach((key,value) -> {
        System.out.println(key + "===" + value));
    });
}

6、Streams API 单线程方式

public void streamsApiOne (Map<Integer,String> map) {
  map.entrySet().stream().forEach((entry) -> {
    System.out.println(entry.getKey() + "====" + entry.getValue());
  });
}

7、Streams API 多线程

public void streamsApiMore(Map<Integer,String> map) {
    map.entrySet().parallelStream().forEach((entry) -> {
        System.out.println(entry.getKey() + "====" + entry.getValue());
    });
}

遍历HashMap_adb_02