// 通过Map.values()遍历所有的value,但不能遍历key for(String v:map.values()){ System.out.println("The value is "+v); }
// 迭代器 EntrySet 方式遍历 -- 性能稍好 一次取值 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()); }
// 迭代器的 KeySet 方式遍历 Iterator<Integer> iterator = map.keySet().iterator(); while (iterator.hasNext()){ Integer key = iterator.next(); System.out.print(key); System.out.print(map.get(key)); }
// For Each EntrySet 方式遍历 -- 推荐,尤其是容量大时 for (Map.Entry<Integer,String> entry: map.entrySet()) { System.out.println("entry.getKey() = " + entry.getKey()); System.out.println("entry.getValue() = " + entry.getValue()); }
// For Each KeySet 方式遍历 -- 普通使用,二次取值(性能差) for (Integer key: map.keySet()) { System.out.println(key); System.out.println(map.get(key)); }
// Lambda 表达式方式遍历 map.forEach((key,value) -> { System.out.print(key); System.out.print(value); });
// Streams API 单线程方式遍历 map.entrySet().stream().forEach((integerStringEntry -> { System.out.println(integerStringEntry.getKey()); System.out.println(integerStringEntry.getValue()); }));
// Streams API 多线程方式遍历 map.entrySet().parallelStream().forEach((integerStringEntry -> { System.out.println(integerStringEntry.getKey()); System.out.println(integerStringEntry.getValue()); }));