Java 将list集合的字符串格式转为Map
List<Object> list = new ArrayList<>();
Map<String,String> map1 = new HashMap<>();
map1.put("fileName","测试1");
map1.put("level","1");
list.add(map1);
Map<String,String> map2 = new HashMap<>();
map2.put("fileName","测试2");
map2.put("level","4");
list.add(map2);
Map<String,String> map3 = new HashMap<>();
map3.put("fileName","测试3");
map3.put("level","9");
list.add(map3);
Map<String,String> map4 = new HashMap<>();
map4.put("fileName",null);
map4.put("level",null);
list.add(map4);
System.out.println("list集合的字符串格式输出:");
System.out.println(list.toString());
List<String> collect = null;
String regex = "\\s*},\\s*";
try {
System.out.println("-----------");
System.out.println("Map类型");
String replace = list.toString().replace(StrUtil.BRACKET_START, StrUtil.EMPTY).replace(StrUtil.BRACKET_END, StrUtil.EMPTY);
collect = Pattern.compile(regex).splitAsStream(replace).collect(Collectors.toList());
List<String> strList = new ArrayList<>(collect.size());
for (int i = 0; i < collect.size(); i++) {
if(i<collect.size()-1){
strList.add(collect.get(i)+"}");
}else{
strList.add(collect.get(i));
}
}
strList.stream().forEach(elem->{
String strReplace = elem.replace(StrUtil.DELIM_START, StrUtil.EMPTY).replace(StrUtil.DELIM_END, StrUtil.EMPTY).replace(StrUtil.SPACE,StrUtil.EMPTY);
// String[] columns = StrUtil.split(strReplace, StrUtil.COMMA);
List<String> columns = StrUtil.split(strReplace, StrUtil.COMMA);
Map<String,String> map = new HashMap<>();
CollUtil.newArrayList(columns).stream().forEach(item->{
// String[] split = StrUtil.split(item, "=");
List<String> split = StrUtil.split(item, "=");
if(split.size()==1){
map.put(split.get(0),null);
}else if(split.size()==2){
map.put(split.get(0),split.get(1));
}
});
System.out.println("我是map:"+map);
});
}catch (Exception e){
e.printStackTrace();
}
结果: