【List<Map<String,String>>】循环遍历,获取key,value(35)

直接上代码:

package com.itheima;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/*
 * List>练习
 */
public class ListMapTest {
 public static void main(String[] args) {
  
  List<Map<String, String>> list = new ArrayList<Map<String, String>>();
  
  Map map1 = new HashMap();
  map1.put("001", "西安");
  map1.put("002", "宝鸡");
  Map map2 = new HashMap();
  
  map2.put("01", "北京");
  map2.put("02", "石家庄");
  
  list.add(map1);
  list.add(map2);
  
  for (Map<String, String> map : list) {
   System.out.println(map);
  }
  System.out.println("1-----------------------");
  for (Map<String, String> map : list) {
   for(String s:map.keySet()) {
    String key = s;
    String value = map.get(key);
    System.out.println("key:"+key);
    System.out.println("value:"+value);
   }
  }
  
  System.out.println("2-----------------------");
  for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = list.get(i);
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                String str = (String) it.next();
                System.out.print("key:"+str+"\t");
                System.out.println("value:"+map.get(str));
            }
        }
  
  System.out.println("3-----------------------"); 
   for (Map<String, String> map : list) {
             for (Map.Entry<String, String> m : map.entrySet()) {
                 System.out.print("key:"+m.getKey() + "    ");
                 System.out.println("value:"+m.getValue());
             }
         }
  System.out.println("4-----------------------"); 
  
 }
}

测试输出:

{001=西安, 002=宝鸡}
{01=北京, 02=石家庄}
1-----------------------
key:001
value:西安
key:002
value:宝鸡
key:01
value:北京
key:02
value:石家庄
2-----------------------
key:001	value:西安
key:002	value:宝鸡
key:01	value:北京
key:02	value:石家庄
3-----------------------
key:001    value:西安
key:002    value:宝鸡
key:01    value:北京
key:02    value:石家庄
4-----------------------

你可能感兴趣的:(ListMap,java)