摘要:list與map集合用法
package com.cht.commons.persistence.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class testCollection {
public static void main(String[] args) {
System.out.println("==============List寫法");
List<Object> list = new ArrayList<Object>();
list.add("dd");
list.add("aa");
list.add("cc");
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
Object string = iterator.next();
System.out.println(string);
}
System.out.println("==============Map寫法");
Map<String, String> map0 = new HashMap<String, String>();
map0.put("name", "zhangsan");
map0.put("***", "female");
String nameString = map0.get("name");
String String = map0.get("***");
System.out.println(nameString + "\n" + String);
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ddd");
map.put("age", 23);
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("name", "ccc");
map1.put("age", 43);
System.out.println("==============Map新增至list,再用iterator取出集合");
List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
lists.add(map);
lists.add(map1);
Iterator<Map<String, Object>> it = lists.iterator();
for (; it.hasNext();) {
Map<String, Object> map2 = it.next();
String name = (String) map2.get("name");
Object age = map2.get("age");
System.out.println("name=" + name + "\nage=" + age);
}
}
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("key1", "value1");
map.put("key2", "value2");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.add(map);
for (Map<String, Object> m : list) {
for (String k : m.keySet()) {
System.out.println(k + " : " + m.get(k));
}
}
for(Map<String,Object> map:list){
for(Map.Entry<String,Object> e:map.entrySet()){
e.getKey() 和 e.getValue() 就是你想要的
}
}
取map的值
Map<String, Object> columns = new HashMap<String, Object>();
columns.put("id", 3);
columns.put("name", "Joan");
columns.put("sex", "女生");
System.out.println("map size=" + columns.size());
for (Entry<String, Object> entry : columns.entrySet()) {
System.out.println(entry.getKey());
System.out.print(" "+entry.getValue());
}
Map<String, Object> columns = new HashMap<String, Object>();
columns.put("id", 3);
columns.put("name", "Joan");
columns.put("sex", "女生");
System.out.println("map size=" + columns.size());
for (Entry<String, Object> entry : columns.entrySet()) {
System.out.println(entry.getKey());
System.out.print(" "+entry.getValue());
}
ref:http://blog.chinaunix.net/uid-26930580-id-3385989.html