list和map的遍历

 

  

list和map是java集合中的必备类,当然他们的遍历也是至关重要的。

list的遍历:

1.for循环

for (Integer each : list) {
    System.out.println(each);
}

2.iterator循环

Iterator<Integer> iterator = list.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }    

3.正规的for循环

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

整个demo如下:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
System.out.println("第一种方式:精简的for循环---------------");
for (Integer each : list) {
	System.out.println(each);
}
System.out.println();
System.out.println("第二种方式:iterator指针---------------");
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
	System.out.println(iterator.next());
}
System.out.println();
System.out.println("第三种方式:正常的for循环---------------");
for (int i = 0; i < list.size(); i++) {
	System.out.println(list.get(i));
}
System.out.println();

 

map的遍历:

使用entrySet()方法遍历:

for (Entry<String, String> each : map.entrySet()) {
    System.out.println(each.getKey() + ":" + each.getValue());
} 

 demo如下:

Map<String, String> map = new HashMap<String, String>();
map.put("1", "小王");
map.put("2", "小李");
map.put("3", "小黑");
for (Entry<String, String> each : map.entrySet()) {
	System.out.println(each.getKey() + ":" + each.getValue());
}

 

转载于:https://www.cnblogs.com/jianpanaq/p/9073475.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值