Java Iterator and Iterable are two key interfaces used to traverse collections in JavaCollectionsFramework. They provide a simple and unified way to access the elements in a collection without directly manipulating the collection itself. In this article, we'll take a deep dive into Iterator and Iterable and show how to use them to simplify collection traversal with demo code.
Iterator is an interface that defines methods for iterating elements in a collection. It provides four methods to traverse collections:
hasNext()
: Check whether there are still elements in the collection. next()
: Returns the next element in the collection. remove()
: Remove the current element from the collection. forEachRem<strong class="keylink">ai</strong>ning(Consumer<? super E> act<strong class="keylink">io</strong>n)
: Perform an operation on the remaining elements in the collection. The Iterator interface is usually used with the Iterator() method of a collection, which returns an Iterator object that can be used to traverse the elements in the collection. For example, the following code shows how to use an Iterator to traverse an ArrayList:
List<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); names.add("Bob"); Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); }
Output:
List<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); names.add("Bob"); for (String name : names) { System.out.println(name); }
Output:
John Mary Bob
Iterator and Iterable are both interfaces for traversing collections, but there are some key differences between them:
remove()
method and the forEachRemaining()
method. Iterable only provides the iterator()
method. Java Iterator and Iterable are two key interfaces in the Java collection framework for traversing collections. They provide a simple and unified way to access the elements in a collection without directly manipulating the collection itself. Iterator provides richer functionality than Iterable, but Iterable is easier to use.
The above is the detailed content of Collection traversal tool: the secret of Java Iterator and Iterable. For more information, please follow other related articles on the PHP Chinese website!