The iterator interface is also a member of the Java Collection framework, unlike the collection of collection and map two series, where the collection and map series are used primarily to act as containers. And iterator, like its name, is primarily used to iterate over the elements in the collection collection, and iterator objects are also known as iterators.
The following 4 methods are defined in the iterator interface:
"Boolean Hasnext (): Returns True if the collection traversed by the iteration has not been traversed.
"Object Next (): Returns the next element inside the collection
Remove (): Deletes the element returned by the previous next () method in the collection
void foreachremaining (Consumer action): Use a lambda expression to iterate over the collection element, which is the default method that java8 adds to iterator
An example is given below
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
public class Bike {
Private String name;//Bike Name
Private double deposit;//deposit
Public Bike () {}
Public Bike (String name,double deposit) {
This.name=name;
This.deposit=deposit;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public double getdeposit () {
return deposit;
}
public void Setdeposit (double deposit) {
This.deposit = deposit;
}
public static void Main (string[] args) {
List<bike> bikes=new arraylist<> ();
Bikes.add (New Bike ("Little Yellow Car", 99));
Bikes.add (New Bike ("motorcycle", 200));
Bikes.add (New Bike ("Xiao Ming Cycle", 100));
Traverse
Iterator It=bikes.iterator ();
while (It.hasnext ()) {
Bike bike= (Bike) it.next ();
SYSTEM.OUT.PRINTLN ("[Model:" +bike.getname () + "] [Deposit:" +bike.getdeposit () + "]");
}
}
The output effect is as follows:
[Model: small yellow car] [Deposit: 99.0]
[Model: Motorcycle Bike] [Deposit: 200.0]
[Model: Xiao Ming Bicycle] [Deposit: 100.0]
JAVA8 enhanced iterator traversal of collection elements