博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java8 增强的Iterator遍历集合元素
阅读量:6914 次
发布时间:2019-06-27

本文共 1268 字,大约阅读时间需要 4 分钟。

Iterator接口也是Java集合框架的成员,与Collection和Map两个系列的集合不一样的是Collection和Map系列主要用于充当容器的作用,而Iterator正如其名字一样是主要用于迭代访问Collection集合中的元素,Iterator对象也被称为迭代器。

Iterator接口里面定义了下面4个方法:

》boolean hasNext():如果被迭代遍历的集合还没有被遍历完,返回True

》Object next():返回集合里面的下一个元素

》remove():删除集合里面上一次next()方法返回的元素

》void forEachRemaining(Consumer action):使用Lambda表达式来遍历集合元素,这是java8为Iterator新增的默认方法

下面给出一个实例

import java.util.ArrayList;

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

public class Bike {

private String name;//自行车名

private double 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("小黄车",99));
bikes.add(new Bike("摩拜单车",200));
bikes.add(new Bike("小鸣单车",100));
//遍历
Iterator it=bikes.iterator();
while(it.hasNext()){
Bike bike=(Bike)it.next();
System.out.println("[车型:"+bike.getName()+"][押金:"+bike.getDeposit()+"]");
}
}

输出效果如下:

[车型:小黄车][押金:99.0]

[车型:摩拜单车][押金:200.0]
[车型:小鸣单车][押金:100.0]

转载于:https://www.cnblogs.com/3s540/p/7172012.html

你可能感兴趣的文章
在主引导记录(MBR)的救援模式下如何重新安装GRUB引导装载程序
查看>>
我的友情链接
查看>>
git的基本使用和示例
查看>>
用户管理
查看>>
从输入 URL 到页面加载完的过程中都发生了什么事情?
查看>>
揭秘Windows Server2012 核心虚拟化技术Hyper-V
查看>>
去除文本中重复的行方法
查看>>
On Stack Replacement and JIT
查看>>
linux 搜索并替换文件内容
查看>>
java--xml文件读取(DOM)
查看>>
Bootstrap-表单
查看>>
hiveserver2连接报错: User: root is not allowed to impersonate anonymous (state=08S01,code=0)
查看>>
Gym 100090D Insomnia
查看>>
springboot shiro配置
查看>>
ZetCode PyQt4 tutorial basic painting
查看>>
WPF RichTextBox的Document属性的序列化与反序列化
查看>>
显示照片方法之一
查看>>
InfoPath读取List到重复表
查看>>
微信公众平台二 文本编辑器与表单工具
查看>>
常用的php函数库
查看>>