遍历List<Map<String,Object>>集合和Map<String,Object>集合

import java.util.*;
public class HelloWorld {
    public static void main(String []args) {
    
    	//定义一个List>集合:
      	List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
      	
      	//定义第一个Map集合,并在其中添加数据
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("1", "a");
        map1.put("2", "b");
        map1.put("3", "c");
        listMaps.add(map1);

		//定义第二个Map集合,并在其中添加数据
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("11", "aa");
        map2.put("22", "bb");
        map2.put("33", "cc");
        listMaps.add(map2);

		//第一种遍历List>集合的方式
        for (Map<String, Object> map : listMaps) {
            for (String s : map.keySet()) {
                System.out.print(map.get(s) + "  ");
            }
        }
        System.out.println();  //打印结果:a  b  c  aa  bb  cc 
      
        System.out.println("========================");
        
        //第二种遍历方式
        for (int i = 0; i < listMaps.size(); i++) {
            Map<String, Object> map = listMaps.get(i);
            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String string = (String) iterator.next();
                System.out.println(map.get(string));
            }
        }
        /**
        打印结果:
        a
		b
		c
		aa
		bb
		cc
		*/
		
        System.out.println("++++++++++++++++++++++++++++");
        
		//第三种遍历方式
        for (Map<String, Object> map : listMaps) {
            for (Map.Entry<String, Object> m : map.entrySet()) {
                System.out.print(m.getKey() + "    ");
                System.out.println(m.getValue());
            }
        }
        /**
        打印结果:
        1    a
		2    b
		3    c
		11    aa
		22    bb
		33    cc
        */
        System.out.println("-----------------------------");

		//List>集合 Map集合的区别:
		 for (Map<String, Object> map : listMaps) {
			System.out.println("List的值:"+ map);
        }
        /**打印结果:
        List的值:{1=a, 2=b, 3=c}
		List的值:{11=aa, 22=bb, 33=cc}
		*/
		
		System.out.println(map1);
		//打印结果:{1=a, 2=b, 3=c}
		
		//遍历map1集合
		for (Map.Entry<String, Object> m : map1.entrySet()) {
			System.out.print(m.getKey() + "    ");
			System.out.println(m.getValue());
		}
		/**打印结果:
		1    a
		2    b
		3    c
		*/
		
		for (Map<String, Object> map : listMaps) {
			map.forEach((e, k) -> {
				if(e.equals("11")){
					k = k + "11";
				}
				System.out.println("e:"+ e + ",k:" + k);
			});
        }
        /** 打印结果:
		e:11,k:aa11
		e:22,k:bb
		e:33,k:cc
		e:1,k:a
		e:2,k:b
		e:3,k:c
		*/
  
    }
}

运行结果:

你可能感兴趣的:(Java,list,java,map)