目录
3. toArray(泛型数组) 方法 + 普通 for 循环
7.lambda 表达式 + 列表的 forEach() 方法
8. lambda 表达式 + 迭代器的 forEachRemaining() 方法
9. Stream 流的 forEach() 和 forEachOrdered() 方法
1. get() 方法 + 普通 for 循环
这是最常用的方式之一,使用 for 循环语句通过的 get() 方法遍历列表的每个元素,示例代码如下:
/**
* 第一种遍历集合的方式:
* get() 方法 + 普通 for 循环
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection01 {
public static void main(String[] args) {
List<Integer> integerList = Stream
.iterate(1, n -> n * 2)
.limit(20)
.collect(Collectors.toList());
for (int i = 0; i < integerList.size(); i++) {
// 使用列表的 get() 方法获取集合的每个元素
Integer integer = integerList.get(i);
System.out.print(integer + " ");
}
}
}
2. toArray() 方法 + 普通 for 循环
除了通过列表本身的方法之外,我们也可以将列表转为 Object 数组,然后进行遍历操作,示例代码如下:
/**
* 第二种遍历集合的方式:
* toArray() 方法 + 普通 for 循环
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection02 {
public static void main(String[] args) {
List<Integer> integerList = IntStream
.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
// 第二种遍历方法
Object[] array = integerList.toArray();
for (int i = 0; i < array.length; i++) {
// 使用数组下标直接获取元素
System.out.print((Integer) array[i] + " ");
}
}
}
3. toArray(泛型数组) 方法 + 普通 for 循环
这个方法可以看作是上一个方法的优化版,可以将集合列表转为指定类型的数组然后再进行遍历操作,示例代码如下:
/**
* 第三种遍历集合的方式:
* toArray(泛型数组) 方法 + 普通 for 循环
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection03 {
public static void main(String[] args) {
List<Double> doubleList = DoubleStream
.generate(()->Math.random() * 10.0)
.limit(18)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
// 第三种遍历方法
Double[] array = doubleList.toArray(new Double[0]);
for (int i = 0; i < array.length; i++) {
// 使用数组下标直接获取元素
System.out.printf("%.2f ", array[i]);
}
}
}
4. 增强 for 循环 —— for-each 循环
相比于普通 for 循环,for-each 循环少了下标的迭代,使得代码看起来更加简洁,示例代码如下:
/**
* 第四种遍历集合的方式:
* 增强 for 循环 —— for-each 循环
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection04 {
public static void main(String[] args) {
// 初始化数据
Person p1 = new Person("智多星吴用", 36);
Person p2 = new Person("呼保义宋江", 41);
Person p3 = new Person("豹子头林冲", 36);
Stream.Builder<Person> builder = Stream.builder();
builder.accept(p1);
builder.accept(p2);
builder.accept(p3);
Stream<Person> personStream = builder.build();
// 使用 Stream 流方法转为列表
List<Person> personList = personStream.collect(Collectors.toList());
// 使用增强 for 循环 —— for-each 循环遍历列表
for (Person person : personList) {
System.out.println(person);
}
}
static class Person {
/** 姓名 */
private String name;
/** 年龄 */
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("age=" + age)
.toString();
}
}
}
5. 迭代器 + while 循环
使用 iterator() 方法可以获取列表的迭代器,迭代器是专门用于遍历集合的工具,不过它也适用于各种 Map 类,示例代码如下:
/**
* 第五种遍历集合的方式:
* 迭代器 + while 循环
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection05 {
public static void main(String[] args) {
// 从控制台读取数据
Scanner in = new Scanner(System.in);
List<String> linkedList = new LinkedList<>();
for (int i = 0; i < 10; i++) {
linkedList.add(in.next());
}
// 获取迭代器
Iterator<String> it = linkedList.iterator();
// 通过迭代器遍历输出
while (it.hasNext()){
System.out.println(it.next());
}
}
}
6. 列表迭代器 + while 循环
此迭代器仅适用于列表,有一些特有的方法,比如从后往前迭代遍历输出,获取下标值等等,示例代码如下:
/**
* 第六种遍历集合的方式:
* 列表迭代器 + while 循环
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection06 {
public static void main(String[] args) {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> integerList = Arrays.asList(arr);
// 获取迭代器
ListIterator<Integer> listIterator1 = integerList.listIterator();
// 通过迭代器遍历输出
while (listIterator1.hasNext()){
System.out.print(listIterator1.next() + " ");
}
System.out.println();
// 此迭代器还可以从指定的下标开始迭代
ListIterator<Integer> listIterator2 = integerList.listIterator(integerList.size());
// 从后往前遍历
while (listIterator2.hasPrevious()) {
System.out.print(listIterator2.previous() + " ");
}
}
}
7.lambda 表达式 + 列表的 forEach() 方法
此方法JDK8后适用,算是一个常用的方法,各类 Map 类也有此方法,示例代码如下:
/**
* 第七种遍历集合的方式:
* lambda 表达式 + 列表的 forEach() 方法
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection07 {
public static void main(String[] args) {
List<Double> arrayList = DoubleStream
.concat(DoubleStream.of(1.23, 2.99, 3.9), DoubleStream.of(4.8, 5.5, 6.7))
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
// 通过方法引用或 lambda 表达式的形式遍历列表
arrayList.forEach(System.out::println);
// Map 类也可以使用此方法
HashMap<String, Object> hashMap = new HashMap<>(2);
hashMap.put("齐天大圣", "孙悟空");
hashMap.put("太上老君", "神仙");
hashMap.forEach((k, v)-> System.out.println(k + "," + v));
}
}
8. lambda 表达式 + 迭代器的 forEachRemaining() 方法
此方法JDK8后适用,通过迭代器的 forEachRemaining() 方法,可以用很简洁的方式遍历列表,示例代码如下:
/**
* 第八种遍历集合的方式:
* lambda 表达式 + 迭代器的 forEachRemaining() 方法
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection08 {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>(4);
arrayList.add("hello");
arrayList.add(",");
arrayList.add("world");
arrayList.add("!");
Iterator<String> iterator = arrayList.iterator();
iterator.forEachRemaining(System.out::print);
}
}
9. Stream 流的 forEach() 和 forEachOrdered() 方法
这两个方法适用于 JDK8 之后,算是集合的补充方法。示例代码如下:
/**
* 第九种遍历集合的方式:
* Stream 流的 forEach() 和 forEachOrdered() 方法
* @author wl
* @date 2022/10/12 11:21
*/
public class TraverseCollection09 {
public static void main(String[] args) {
Random random = new Random();
List<Integer> integerList = Stream
.generate(() -> random.nextInt(10) + 1)
.limit(10)
.collect(Collectors.toList());
// 使用 Stream 流的遍历方法
integerList
.stream()
.forEach(i -> System.out.print(i + " "));
System.out.println();
// 也可这样写
Stream.of("zhangsan", "lisi", "wangwu", "liuliu", "liuliu")
.filter(s -> s.startsWith("l"))
.limit(2)
.sorted()
.forEach(str -> System.out.print(str + " "));
System.out.println();
// forEachOrdered() 方法多线程中适用,可以保证遍历的顺序是有序的
integerList
.stream()
.forEachOrdered(i -> System.out.print(i + " "));
}
}
不过你要是只想遍历集合的话,用集合自身的 forEach() 方法一般就够用了,犯不着转成 stream 再遍历