Java 将list集合的字符串格式转为Map

Java 将list集合的字符串格式转为Map

List list = new ArrayList<>();
Map map1 = new HashMap<>();
map1.put("fileName","测试1");
map1.put("level","1");
list.add(map1);

Map map2 = new HashMap<>();
map2.put("fileName","测试2");
map2.put("level","4");
list.add(map2);

Map map3 = new HashMap<>();
map3.put("fileName","测试3");
map3.put("level","9");
list.add(map3);

Map map4 = new HashMap<>();
map4.put("fileName",null);
map4.put("level",null);
list.add(map4);

System.out.println("list集合的字符串格式输出:");
System.out.println(list.toString());

List 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 strList = new ArrayList<>(collect.size());
	for (int i = 0; i < collect.size(); i++) {
		if(i{
		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 columns = StrUtil.split(strReplace, StrUtil.COMMA);
		Map map = new HashMap<>();
		CollUtil.newArrayList(columns).stream().forEach(item->{
//                    String[] split = StrUtil.split(item, "=");
			List 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();
} 
  

结果:

Java 将list集合的字符串格式转为Map_第1张图片

你可能感兴趣的:(Java,Java,字符串,将的字符串格式转为Map)