一,JDK8以前版本,使用entrySet()遍历Map类集合,只是遍历了一次就把key和value都放到了entry中,效率更高。
而不是用keySet()方式进行遍历,keySet()其实是遍历了两次,一次是转为Iterator对象,另一次是从hashfMap中取出key对应的value。
Map<String, String> map = new HashMap<>();
map.put("1", "111");
map.put("2", "222");
map.put("3", "333");
Set<Entry<String, String>> entrySet = map.entrySet();
for(Entry<String, String> entry:entrySet) {
System.out.println(entry.getKey()+","+entry.getValue());
}
二,JDK8版本,使用forEach()遍历
//遍历Map集合
Map<String, String> map = new HashMap<>();
map.put("1", "111");
map.put("2", "222");
map.put("3", "333");
map.forEach((key,value)->{
System.out.println(key+","+value);
});
//遍历List集合
List<User> list = new ArrayList<>();
list.forEach(user -> {
System.out.println(user.getId()+","+user.getName());
});