HashMap的7种遍历方式

注意:首先要弄清楚EntrySet和KeySet的区别,HashMap遍历中,keySet是键的集合,Set里面的类型是key类型,entrySet是键-值对的集合,Set里面的类型是Map.Entry

1.keySet是键的集合

Map map=new HashMap();

Iterator it=map.keySet().iterator();

Object key ,value;

while(it.hasNext()){

key=it.next();

value=map.get(key);

System.out.println(key+":"+value);

}
2.entrySet是键-值对的集合

Map map=new HashMap();

Iterator it=map.entrySet().iterator();

Object key ,value;

while(it.hasNext()){

Map.Entry entry = (Map.Entry)it.next();

key=entry.getKey();

value=entry.getValue();

System.out.println(key+"="+value);

}

1.iterator迭代器进行Entry遍历(此方法效率最佳)

Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()){
        Map.Entry<Integer, String> next = iterator.next();
        System.out.println(next.getKey());
        System.out.println(next.getValue());
    }

2.iterator迭代器进行KeySet遍历

Iterator<Integer> iterator = map.keySet().iterator();
    while (iterator.hasNext()){
        Integer key = iterator.next();
        System.out.print(key);
        System.out.print(map.get(key));
    }

3.ForEach的EntrySet方式进行遍历

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

4.ForEach的KeySet方式进行遍历

 for (Interger key: map.keySet()) {
     	System.out.print(key);
        System.out.print(map.get(key));
    }

5.Lambda 表达式进行遍历

    map.forEach((key,value) -> {
        System.out.print(key);
        System.out.print(value);
    });

6. Streams API 单线程的方式进行遍历

    map.entrySet().stream().forEach((integerStringEntry -> {
        System.out.println(integerStringEntry.getKey());
        System.out.println(integerStringEntry.getValue());
    }));

7.Streams API 多线程的方式进行遍历

    map.entrySet().parallelStream().forEach((integerStringEntry -> {
        System.out.println(integerStringEntry.getKey());
        System.out.println(integerStringEntry.getValue());
    }));

你可能感兴趣的:(java,开发语言)