个人主页
JavaSE系列专栏
本篇博客主要以介绍集合的四种遍历方法,for循环遍历,增强for循环,迭代器,Stream流遍历
List<Integer> arrayList=new ArrayList<>();
Collections.addAll(arrayList,1,2,2,3,4,5);
arrayList.forEach(e->{ System.out.println(e); });
【List集合:(for循环)】
List<Integer> arrayList=new ArrayList<>();
List<Integer> linkedList=new LinkedList<>();
Collections.addAll(arrayList,1,2,3,4,5);
Collections.addAll(linkedList,1,2,3,4,5);
for (int i = 0; i <arrayList.size() ; i++) {
System.out.println(arrayList.get(i));
}
不能遍历删除元素,否则会报并发修改异常
)【List集合:(foreach循环)】
List<Integer> arrayList=new ArrayList<>();
List<Integer> linkedList=new LinkedList<>();
Collections.addAll(arrayList,1,2,3,4,5);
Collections.addAll(linkedList,1,2,3,4,5);
for (Integer integer : linkedList) {
System.out.println(integer);
}
【Set集合:(foreach循环)】
Set<Integer> hashSet=new HashSet<>();
Set<Integer> treeSet=new TreeSet<>();
Collections.addAll(hashSet,1,2,3,4,5);
Collections.addAll(treeSet,1,2,3,4,5);
for (Integer integer : treeSet) {
System.out.println(integer);
}
Set<Integer> hashSet=new HashSet<>();
Set<Integer> treeSet=new TreeSet<>();
Collections.addAll(hashSet,1,2,3,4,5);
Collections.addAll(treeSet,1,2,3,4,5);
Iterator<Integer> iterator=hashSet.iterator();
while (iterator.hasNext()){
Integer e=iterator.next();//拿到下一个元素
//经常与remove()相配合来删除元素
if(e==2){
iterator.remove();
}
}
Set<Integer> hashSet=new HashSet<>();
Set<Integer> treeSet=new TreeSet<>();
Collections.addAll(hashSet,1,2,3,4,5);
Collections.addAll(treeSet,1,2,3,4,5);
hashSet.stream().forEach(e->{ System.out.println(e); });
treeSet.stream().forEach(e->{System.out.println(e);});