List 的遍历
ArrayList<String> list = new ArrayList<>();
===1 forEach循环遍历===
list.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
// JDK8开始 出现lambda表达式 新语法
list.forEach((s) -> {
System.out.println(s);
});
===2 增强for循环遍历===
System.out.println();
for (String s : list) {
System.out.println(s);
}
====3 迭代器遍历======
System.out.println();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Set的遍历
Set<String> set1 = new HashSet<>();
==1增强for遍历==
for (String s : set1) {
System.out.println(s);
}
==2 迭代器遍历==
Iterator<String> iterator = set1.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
==3 forEach 匿名内部类==
set1.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
==3 lambda表达式==
set1.forEach((a) -> {
System.out.println(a);
});
Map的遍历
Map<Integer, String> map = new HashMap<>();
==1 先获取所有的Key对象,再依次根据Key对象取对应的value对象==
Set<Integer> keySet = map.keySet();
for (Integer key : keySet) {
System.out.println(key + "=" + map.get(key));
}
==2 forEach==
map.forEach(new BiConsumer<Integer, String>() {
@Override
public void accept(Integer key, String value) {
System.out.println(key + "=" + value);
}
});
==2 lambda表示==
map.forEach((k, v) -> {
System.out.println(k + "=" + v);
});
==3 entrySet集合遍历==
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
for (Map.Entry<Integer, String> entry : entrySet) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
标签:遍历,iterator,System,println,forEach,集合,out
From: https://www.cnblogs.com/jh0129/p/17216678.html