Java遍历Map的四种方法及对比

package cn.sf.util;
2.
3.import java.util.HashMap;
4.import java.util.Iterator;
5.import java.util.Map;
6.import java.util.Map.Entry;
7.import java.util.Set;
8.
9.public class TestMap {
10.
11. /**
12. * 方法一 在for-each循环中使用entries来遍历
13. * 这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用
14. */
15. public void testMap1(){
16. Map<String, String> map = new HashMap<String, String>();
17. map.put("map1", "1");
18. map.put("map2", "2");
19. map.put("map3", "3");
20.
21. Set<String> keys = map.keySet();
22. for (String key : keys) {
23. System.out.println(key+"---"+map.get(key));
24. }
25. }
26. /**
27. * 方法一 :如果只需要map中的键或者值,你可以通过keySet或values来实现遍历
28. * 比entrySet性能
29. */
30. public void testMap2(){
31. Map<String, String> map = new HashMap<String, String>();
32. map.put("map1", "1");
33. map.put("map2", "2");
34. map.put("map3", "3");
35.
36. Set<String> keys = map.keySet();
37. for (String key : keys) {
38. System.out.println("key:"+map.get(key));
39. }
40. for (String value : map.values()) {
41. System.out.println("value:"+value);
42. }
43. }
44. /**
45. * 方法三:使用Iterators
46. */
47. public void testMap3(){
48. Map<String, String> map = new HashMap<String, String>();
49. map.put("map1", "1");
50. map.put("map2", "2");
51. map.put("map3", "3");
52. Iterator<Entry<String, String>> iterators = map.entrySet().iterator();
53. while(iterators.hasNext()){
54. Entry<String, String> entry = iterators.next();
55. System.out.println(entry.getKey()+"---"+entry.getValue());
56. }
57. }
58.
59. /**
60. * 方法四 :通过键找值遍历(效率低)
61. */
62. public void testMap4(){
63. Map<String, String> map = new HashMap<String, String>();
64. map.put("map1", "1");
65. map.put("map2", "2");
66. map.put("map3", "3");
67.
68. for (Map.Entry<String, String> entry : map.entrySet()) {
69. System.out.println(entry.getKey()+"--"+entry.getValue());
70. }
71. }
72. public static void main(String[] args) {
73. TestMap testMap = new TestMap();
74. testMap.testMap1();
75. System.out.println();
76. testMap.testMap2();
77. System.out.println();
78. testMap.testMap3();
79. System.out.println();
80. testMap.testMap4();
81. }
82.}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值