1. 迭代器遍历
public static void getSet1(Set
<String> set
) {
Iterator
<String> iterator
= set
.iterator();
while (iterator
.hasNext()) {
String value
= iterator
.next();
System
.out
.print(value
+ " ");
}
}
2. 增强for
public static void getSet2(Set
<String> set
) {
for (String s
: set
) {
System
.out
.print(s
+ " ");
}
}
3. Collection中的toArray()方法遍历
public static void getSet3(Set
<String> set
) {
Object
[] objs
= set
.toArray();
for (int i
= 0; i
< objs
.length
; i
++) {
System
.out
.print(objs
[i
] + " ");
}
}
4. Lambda表达式
同理相同的代码可以遍历List集合
遍历Set集合
public static void getSet4(Set
<String> set
) {
set
.forEach(n
-> System
.out
.println(n
));
set
.forEach(System
.out
::println
);
}
遍历List集合
list
.forEach(n
-> System
.out
.println(n
));
System
.out
.println("=====4.使用lambda表达式遍历List集合=====");
list
.forEach(System
.out
::println
);
转载请注明原文地址: https://lol.8miu.com/read-1430.html