Home >Java >javaTutorial >How to use iterator in java
Iterator in Java is a tool used to traverse collections. Usage methods include: Obtaining an Iterator: Use the iterator() method of the Collection interface. Loop through the collection: use hasNext() to check if the next element exists, use next() to get the current element and move to the next element.
Usage of Iterator in Java
What is Iterator?
The Iterator interface is a tool in the Java programming language for traversing collections. It provides a set of methods that allow the programmer to access each element in the collection sequentially.
Usage of Iterator:
Get Iterator:
iterator()
Method gets the Iterator of the collection. Loop through the collection:
hasNext()
method to check whether the Iterator still exists The next element. next()
method to get the current element and move to the next element. Sample code:
<code class="java">// 创建一个字符串集合 Set<String> names = new HashSet<>(); names.add("Alice"); names.add("Bob"); names.add("Carol"); // 获取集合的 Iterator Iterator<String> iterator = names.iterator(); // 循环遍历集合 while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); }</code>
Advantages:
Note:
Iterator is a read-only interface and cannot be used to modify elements in the collection. If you need to modify the collection, you need to use other methods, such as List.set()
or Map.put()
.
The above is the detailed content of How to use iterator in java. For more information, please follow other related articles on the PHP Chinese website!