Home  >  Article  >  Java  >  java8--Explanation on how to enhance Iterator to traverse collection elements

java8--Explanation on how to enhance Iterator to traverse collection elements

巴扎黑
巴扎黑Original
2017-07-17 16:57:131549browse

The Iterator interface is also a member of the Java collection framework. Unlike the Collection and Map series, the Collection and Map series are mainly used to act as containers, while Iterator, as its name suggests, is mainly used to iteratively access Collections. The elements in the collection, Iterator objects are also called iterators.

The Iterator interface defines the following four methods:

》boolean hasNext(): If the collection being iterated through has not been traversed completely, return True

》Object next():Returns the next element in the collection

》remove():Removes the last next() method return in the collection Elements

》void forEachRemaining(Consumer action): Use Lambda expressions to traverse collection elements. This is the new default method added by java8 for Iterator

given below An instance

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class Bike {

private String name;//Bicycle 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 bikes=new ArrayList<>();
## bikes.add(new Bike("小黄车",99));
bikes.add(new Bike("Mobike",200));## bikes.add(new Bike("Xiaoming Bicycle ",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: Xiaohuang Car][Deposit: 99.0]
[Model: Mobike][Deposit: 200.0]

[Model: Xiaoming Bicycle][Deposit: 100.0]

The above is the detailed content of java8--Explanation on how to enhance Iterator to traverse collection elements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn