java集合的运用,把数组和对象的json格式,转换成对象和数组的格式

本文介绍了一个实用的Java工具类,该类可以将List<HashMap>类型的集合转换为Map<String, List>类型的数据结构,便于进行进一步的数据处理和分析。文章通过具体示例展示了转换方法的实现细节。
package com.yanshu.utils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.jboss.jandex.Main;


import com.alibaba.fastjson.JSON;


public class MapUtil {


public static String ListTojson(List<HashMap> map2){
if(map2.size()==0){
return "{}";
}
Map<String,List> map=new HashMap<String,List>();
Set<String> set=map2.get(0).keySet();
for (String setchild : set) {
map.put(setchild, new ArrayList<>());
}


for (int i = 0; i < map2.size(); i++) {
for (String str : set) {
map.get(str).add(map2.get(i).get(str)==null?0:map2.get(i).get(str));
}
}
return   JSON.toJSONString(map);
}

public static String  ListTurnMap(List<HashMap> maps)
{
//如何长度等于0,返回空
if(maps.size()==0)
{
return "{}";
}
Map<String,List> map=new HashMap<>();
Set<String> set=maps.get(0).keySet();//获取List<HashMap> maps的第一个键
System.out.println("set--->>>"+set);
for (String setchild : set) {
map.put(setchild,new ArrayList<>());//[{tom=23, mary=12}, {tom=33, mary=22}]转换成{tom=[], mary=[]}
}
System.out.println("map-->>"+map);
//填值
for(int i=0;i<maps.size();i++)
{
for (String str : set) {
//map.get(str).add(map2.get(i).get(str)==null?0:map2.get(i).get(str));
map.get(str).add(maps.get(i).get(str)==null?0:maps.get(i).get(str));

}
}



return   JSON.toJSONString(map);//{"tom":[23,33],"mary":[12,22]}

}

public static void main(String[] args) {
Map map1=new HashMap<>();
Map map2=new HashMap<>();
map1.put("tom",23);
map1.put("mary",12);
map2.put("tom",33);
map2.put("mary",22);
List list=new ArrayList();
list.add(map1);
list.add(map2);
System.out.println(list);
String listTojson = ListTurnMap(list);

System.out.println(listTojson);






}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值