Java遍历集合(如List
, Set
, Map
等)通常有多种方法。遍历集合的方式,包括传统for循环、增强的for循环(也称"for-each"循环)、迭代器(Iterator
)以及流(Stream
)API。
示例:
for循环遍历List:
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
for循环(for-each)遍历集合:
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
迭代器(Iterator)遍历集合:
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
流(Stream)API遍历集合:
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
list.stream().forEach(System.out::println);
遍历Map:
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// 遍历键
for (String key : map.keySet()) {
System.out.println(key);
}
// 遍历值
for (Integer value : map.values()) {
System.out.println(value);
}
// 遍历键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
标签:map,遍历,Java,list,System,println,集合,out From: https://blog.csdn.net/xuann/article/details/145125355