遍历MAP的四种方法(增强for循环)

来源:互联网 发布:阿里云 bd 待遇 编辑:程序博客网 时间:2024/06/05 09:18

增强for循环:


设计的本意:抛弃迭代器
增强for循环只能遍历数组和实现了Iteratable接口的对象。
语法:
    for(元素的类型 变量名:数组或实现了Iteratable接口的对象){
    System.out.println(变量名);

    }

增强for循环的特点:只适合取数据。要想在遍历时改元素的值,请使用传统for循环。


遍历MAP的四种方法:

//增强for循环public class Demo {//传统方式遍历Map@Testpublic void test3(){Map map = new LinkedHashMap();map.put("a", "aaa");map.put("b", "bbb");map.put("c", "ccc");Set keys = map.keySet();Iterator it = keys.iterator();while(it.hasNext()){String key = (String)it.next();String value = (String) map.get(key);System.out.println(key+"="+value);}}@Test//增强for遍历map方式一public void test31(){Map map = new LinkedHashMap();map.put("a", "aaa");map.put("b", "bbb");map.put("c", "ccc");Set keys = map.keySet();for(Object obj:keys){String key = (String)obj;String value = (String) map.get(key);System.out.println(key+"="+value);}}//传统方式遍历Map@Testpublic void test4(){Map map = new LinkedHashMap();map.put("a", "aaa");map.put("b", "bbb");map.put("c", "ccc");Set me = map.entrySet();Iterator it = me.iterator();while(it.hasNext()){Map.Entry m = (Map.Entry)it.next();String key = (String) m.getKey();String value = (String)m.getValue();System.out.println(key+"="+value);}}@Test//增强for循环遍历map方式二public void test41(){Map map = new LinkedHashMap();map.put("a", "aaa");map.put("b", "bbb");map.put("c", "ccc");for(Object obj:map.entrySet()){Map.Entry me = (Map.Entry )obj;String key = (String) me.getKey();String value = (String)me.getValue();System.out.println(key+"="+value);}}}



阅读全文
0 0
原创粉丝点击