增强型for循环与Map集合的遍历

来源:互联网 发布:古代军官知乎 编辑:程序博客网 时间:2024/05/16 07:26
Map接口的遍历有以下几种方法:
  1. 使用map.values()方法,先把value的值都放在一个Collection集合中。
  2. 使用map.entrySet()方法。
  3. 使用map.keySet()方法。
其实对于Map接口进行遍历操作是很少的,通常对其都是进行查询操作。for-each循环在Java 5中被引入,所以该方法只能应用于Java 5或更高的版本中,在集合框架中发挥着重要的用处。



关于增强型for循环


语法格式:
for(集合内储存类型 变量名 : 集合变量名)
举例:

List<String> list = new ArrayList<String>();list.add("wang");list.add("hong");for(String str : list)    System.out.println(str);

打印的结果是list集合中的数据


增强型for循环使用须知:

  1. 增强for循环只能用在数组或实现Interable接口的集合类上
  2. 如果遍历一个空的Map对象,for-each循环将抛出NullPointerException异常
  3. 增强for循环和iterator遍历的效果是一样的,也就说增强for循环的内部也就是调用iteratoer实现的。但是增强for循环有些缺点,例如不能在增强循环里动态的删除集合内容。不能获取下标等
  4. 增强型for循环只适合取数据,不会更改数据,如对更改数据有要求需要使用传统for循环方式



关于Map集合的遍历


Map集合没有实现Interable接口,因此无法直接使用增强for循环,需要转成相应的set集合,Map集合无法直接迭代
Map集合遍历的传统方式:

第一种方式:迭代

1.使用keySet()迭代

    @Testpublic void test() {    Map map = new HashMap();    map.put("1","aaa");    map.put("2","bbb");    map.put("3","ccc");    //迭代遍历Map集合的第一种方式    Set set = map.keySet();    Iterator it = set.iterator();    while(it.hasNext()){        String key = (String) it.next();        String value = (String) map.get(key);        System.out.println(key + "=" + value);    }}

同时应注意,若使用HashMap()方法,在保存数据的时候采用哈希算法进行保存,因此在取数据时的打印输出不会按照存入的顺序,若对顺序有要求,可以采用LinkedHashMap方法,采用线性链表存储数据。

2.使用entrySet()迭代
Entry是一个键值对对象,包含key和value两个属性,可以通过getKey()获得key值,也可以通过getValue()获得value值。entrySet实现了Set接口,可以用以遍历Map对象。

@Testpublic void test() {    Map map = new HashMap();    map.put("1","aaa");    map.put("2","bbb");    map.put("3","ccc");    //迭代遍历Map集合的第二种方式    Set set = map.entrySet();    Iterator it = set.iterator();    while(it.hasNext()){        Entry entry = (Entry) it.next();        String key = (String) entry.getKey();        String value = (String) entry.getValue();        System.out.println(key + "=" + value);    }}

第二种方式:增强型for循环

1.for循环&keySet()

    @Testpublic void test() {    Map map = new HashMap();    map.put("1","aaa");    map.put("2","bbb");    map.put("3","ccc");    //增强型for循环遍历Map集合    for(Object obj : map.keySet()) {        String key = (String) obj;//取到每一个key值        String value = (String) map.get(key);        System.out.println(key + "=" + value);    }}

2.for循环&entrySet()

    @Testpublic void test() {    Map map = new HashMap();    map.put("1","aaa");    map.put("2","bbb");    map.put("3","ccc");    //增强型for循环遍历Map集合    for(Object obj : map.entrySet()) {        Map.Entry entry = (Map.Entry) obj;        String key = (String) entry.getKey();        String value = (String) entry.getValue();        System.out.println(key + "=" + value);    }}
0 0
原创粉丝点击