案例目的将List<Map<String,Object>> 遍历,按条件取得map里面符合要求的元素,将其有序的放到自定义的一个Edit类中,模拟形成一个新的Map对象:
Edit类:
public class Edit {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
测试类:
public class Test {
public List<Map<String,Object>> see() {
Map<String, Object> map = new HashMap<>();
map.put("wkx", "666");
map.put("laq", "999");
map.put("key", "datetime");
map.put("value", "2000");
Map<String, Object> map2 = new HashMap<>();
map2.put("wkx2", "666");
map2.put("laq2", "999");
map2.put("key", "dateid");
map2.put("value", "1000");
List<Map<String, Object>> listmap = new LinkedList<>();
listmap.add(map);
listmap.add(map2);
return listmap;
}
public static void main(String[] args) {
Test a = new Test();
List<Edit> edits=new LinkedList<>();
List<List<Edit>> mapplus =new LinkedList<>();
List list = a.see();
for (int i=0;i<list.size();i++){
Edit edit = new Edit();
Map<String, Object> map = (Map) list.get(i);
for (Map.Entry entry : map.entrySet()) {
if ("key".equals(entry.getKey())) {
edit.setKey((String)entry.getValue());
}
if ("value".equals(entry.getKey())) {
edit.setValue((String) entry.getValue());
}
}
if (edit.getKey()!=null&&edit.getValue()!=null) {
edits.add(edit);
}
}
mapplus.add(edits);
System.out.println(list.toString());
}
}
将mapplus里面的内容全部存储到数据库中的一个字段中:
public String list2string(List<List<Edit>> list){
//但我们得到一个全新的list<map>时,我们要把它里面所有的map(包括key和value都存到数据库中的一个字段中去)
// 我们用到jsoAarray
JSONArray jsonArray = new JSONArray();
//逐渐遍历之前取得的mapplus
list.forEach(n->{
n.forEach(e -> {
String key = e.getKey();
String value = e.getValue();
});
jsonArray.add(n);
});
return JSONArray.toJSONString(jsonArray);
}
//测试
mapplus.add(edits);
String ss = new SortByLetter().list2string(mapplus);
System.out.println(ss);