List<String[]> 数组集合转 List<Map<String,String>>集合
今天遇到一地方是从表中读取数据到List中,然后要把数据返回到前端展示,所以要把List<String[]>转为List<Map<String,String>> 写了一个简单的小测试,供以后参考
public class Test01 {
public static void main(String[] args) {
String[] str = {“id”,“name”,“age”,“gender”}; //表示表头信息
List<String[]> list = new ArrayList<>(); //存放表数据
String[] s1 = {"1","小明","18","男"}; //从表中读取出来的数据
String[] s2 = {"2","小强","19","男"};
String[] s3 = {"3","小花","17","女"};
String[] s4 = {"4","小红","18","女"};
list.add(s1); //把列数据添加到集合中
list.add(s2);
list.add(s3);
list.add(s4);
List<Map<String,String>> mapList = new ArrayList<>();
for (int i = 0; i <list.size() ; i++) {
Map<String,String> map = new HashMap<>(); //每循环一条数据就创建一个Map
for(int j = 0; j < list.get(i).length; j++){
map.put(str[j],list.get(i)[j]); //表头和字段的长度是相同的,可以同用索引
}
mapList.add(map);
}
//打印给果
for(Map<String,String> ma : mapList){
for(Map.Entry<String,String> m : ma.entrySet()){
System.out.println(m.getKey()+"---"+m.getValue());
}
System.out.println("-------------");
}
}
}
打印给果如下: