Stream流实现Object与map相互转化
时间: 2023-06-16 18:02:09 浏览: 223
可以通过Java 8中的Stream API实现Object与Map相互转换,具体步骤如下:
将Object转换为Map:
1. 首先需要获取该Object的所有字段,可以通过反射实现,如下:
```
Field[] fields = obj.getClass().getDeclaredFields();
```
2. 然后通过Stream将字段转换为Map,如下:
```
Map<String, Object> map = Arrays.stream(fields)
.peek(field -> field.setAccessible(true))
.collect(Collectors.toMap(Field::getName, field -> {
try {
return field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}));
```
将Map转换为Object:
1. 首先需要获取该Object的Class对象,如下:
```
Class clazz = obj.getClass();
```
2. 然后通过Stream将Map中的键值对转换为Object的字段,如下:
```
map.forEach((key, value) -> {
try {
Field field = clazz.getDeclaredField(key);
field.setAccessible(true);
field.set(obj, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
});
```
完整代码如下:
```
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class ObjectMapConverter {
public static Map<String, Object> objectToMap(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
Map<String, Object> map = Arrays.stream(fields)
.peek(field -> field.setAccessible(true))
.collect(Collectors.toMap(Field::getName, field -> {
try {
return field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}));
return map;
}
public static void mapToObject(Map<String, Object> map, Object obj) {
Class clazz = obj.getClass();
map.forEach((key, value) -> {
try {
Field field = clazz.getDeclaredField(key);
field.setAccessible(true);
field.set(obj, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
});
}
public static void main(String[] args) {
Person person = new Person("Tom", 20);
Map<String, Object> map = objectToMap(person);
System.out.println(map);
Person newPerson = new Person();
mapToObject(map, newPerson);
System.out.println(newPerson);
}
}
class Person {
private String name;
private int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
阅读全文