List<Map<String,Object>> 转成 List<List<String>>
时间: 2023-10-14 22:48:02 浏览: 114
可以通过遍历原始列表,并将每个 Map 的值转换为 String 类型,然后将结果添加到新的列表中。下面是一个示例代码:
```java
List<Map<String, Object>> originalList = new ArrayList<>();
// 假设原始列表中有数据
List<List<String>> newList = new ArrayList<>();
for (Map<String, Object> map : originalList) {
List<String> stringList = new ArrayList<>();
for (Object value : map.values()) {
stringList.add(String.valueOf(value));
}
newList.add(stringList);
}
// 现在 newList 是 List<List<String>> 类型的列表,其中每个元素都是字符串类型的值
```
请注意,在转换过程中,我们使用 `String.valueOf()` 方法将 Object 类型的值转换为 String 类型。
相关问题
String类型转换成List<Map<String,Object>>
可以使用以下方法将String类型转换为List<Map<String, Object>>:
1. 使用JSON库进行转换:
```java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
String jsonString = "[{\"key1\":\"value1\",\"key2\":\"value2\"},{\"key1\":\"value3\",\"key2\":\"value4\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> resultList = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>(){});
// 输出结果
System.out.println(resultList);
```
2. 使用Gson库进行转换:
```java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
String jsonString = "[{\"key1\":\"value1\",\"key2\":\"value2\"},{\"key1\":\"value3\",\"key2\":\"value4\"}]";
Gson gson = new Gson();
List<Map<String, Object>> resultList = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>(){}.getType());
// 输出结果
System.out.println(resultList);
```
3. 使用Jackson库进行转换:
```java
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
String jsonString = "[{\"key1\":\"value1\",\"key2\":\"value2\"},{\"key1\":\"value3\",\"key2\":\"value4\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> resultList = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>(){});
// 输出结果
System.out.println(resultList);
```
Object转换List<Map<String,Object>>
要将Object转换为List<Map<String,Object>>,可以使用Java8的Stream API和lambda表达式来实现。具体步骤如下:
1. 将Object对象转换为Map<String,Object>对象,可以使用反射机制获取对象的属性和值,然后将其存储到Map中。
2. 将Map对象添加到List中。
3. 重复步骤1和步骤2,直到所有的Object对象都被转换为Map对象并添加到List中。
4. 返回List<Map<String,Object>>对象。
下面是一个示例代码:
```
List<Object> objectList = new ArrayList<>();
// 假设objectList中已经有了多个Object对象
List<Map<String,Object>> mapList = objectList.stream()
.map(obj -> {
Map<String,Object> map = new HashMap<>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String key = propertyDescriptor.getName();
Method getter = propertyDescriptor.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
})
.collect(Collectors.toList());
```