foreach遍历二维数组java_java关于集合的遍历与增强for循环(foreach)的使用

1 //增强For循环

2 public class MapTest {

3

4 public static void main(String[] args) {

5 // 创建一个HashMap对象,并加入了一些键值对。

6 Map maps = new HashMap();

7 maps.put("111", "java111");

8 maps.put("222", "java222");

9 maps.put("333", "java333");

10 maps.put("444", "java444");

11 maps.put("555", "java555");

12

13 // 传统的遍历map集合的方法1; keySet()

14 //traditionalMethod1(maps);

15 // 传统的遍历map集合的方法2; entrySet()

16 //traditionalMethod2(maps);

17 // 使用增强For循环来遍历map集合方法1; keySet()

18 //strongForMethod1(maps);

19 // 使用增强For循环来遍历map集合方法2; entrySet()

20 strongForMethod2(maps);

21 }

22

23 private static void strongForMethod2(Map maps) {

24 Set> set = maps.entrySet();

25 for (Entry entry : set) {

26 String key = entry.getKey();

27 String value = entry.getValue();

28 System.out.println(key + " : " + value);

29 }

30 }

31

32 private static void strongForMethod1(Map maps) {

33 Set set = maps.keySet();

34 for (String s : set) {

35 String key = s;

36 String value = maps.get(s);

37 System.out.println(key + " : " + value);

38 }

39 }

40

41 // 使用entrySet()方法,获取maps集合中的每一个键值对,

42 private static void traditionalMethod2(Map maps) {

43 Set> sets = maps.entrySet();

44 // 取得迭代器遍历出对应的值。

45 Iterator> it = sets.iterator();

46 while (it.hasNext()) {

47 Map.Entry entry = (Entry) it.next();

48 String key = entry.getKey();

49 String value = entry.getValue();

50 System.out.println(key + " : " + value);

51 }

52 }

53

54 // 使用keySet()方法,获取maps集合中的所有键,遍历键取得所对应的值。

55 private static void traditionalMethod1(Map maps) {

56 Set sets = maps.keySet();

57 // 取得迭代器遍历出对应的值。

58 Iterator it = sets.iterator();

59 while (it.hasNext()) {

60 String key = it.next();

61 String value = maps.get(key);

62 System.out.println(key + " : " + value);

63 }

64 }

65 }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值