我用了三种方式,1:forEach循环;2:for循环;3:stream方法
java
package org.springblade.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
@org.junit.jupiter.api.Test
public void aaa() {
User user1 = new User("张三", 10, 1);
User user2 = new User("李四 ", 11, 1);
User user3 = new User("王五", 12, 0);
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
//我这里都转为了List<Map<String, Object>>数组,也可以转换为一个新的实体类(自行创建)
//使用forEach循环转化
List<Map<String, Object>> infosFromForEach = new ArrayList<>();
users.forEach(user -> {
Map<String, Object> singleMap = new HashMap<>();
singleMap.put("age", user.getAge());
singleMap.put("gender", user.getGender());
infosFromForEach.add(singleMap);
});
//使用for循环转化
List<Map<String, Object>> infosFromFor = new ArrayList<>();
for (User user : users) {
Map<String, Object> singleMap = new HashMap<>();
singleMap.put("age", user.getAge());
singleMap.put("gender", user.getGender());
infosFromFor.add(singleMap);
}
//使用stream流实现转换
List<Map<String, Object>> collect = users.stream().map(user -> {
Map<String, Object> singleMap = new HashMap<>();
singleMap.put("age", user.getAge());
singleMap.put("gender", user.getGender());
return singleMap;
}).collect(Collectors.toList());
}
}
class User {
//姓名
private String name;
//年龄
private Integer age;
//性别:0:女;1:男
private Integer gender;
public User() {
}
public User(String name, Integer age, Integer gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public User setName(String name) {
this.name = name;
return this;
}
public Integer getAge() {
return age;
}
public User setAge(Integer age) {
this.age = age;
return this;
}
public Integer getGender() {
return gender;
}
public User setGender(Integer gender) {
this.gender = gender;
return this;
}
}