我用了三种方式,1:forEach循环;2:for循环;3:stream方法

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.Testpublic void aaa() {User user1 = new User("张三", 10, 1);User user2 = new User("李四 ", 11, 1);User user3 = new User("王五", 12, 0);List users = new ArrayList();users.add(user1);users.add(user2);users.add(user3);//我这里都转为了List<Map>数组,也可以转换为一个新的实体类(自行创建)//使用forEach循环转化List<Map> infosFromForEach = new ArrayList();users.forEach(user -> {Map singleMap = new HashMap();singleMap.put("age", user.getAge());singleMap.put("gender", user.getGender());infosFromForEach.add(singleMap);});//使用for循环转化List<Map> infosFromFor = new ArrayList();for (User user : users) {Map singleMap = new HashMap();singleMap.put("age", user.getAge());singleMap.put("gender", user.getGender());infosFromFor.add(singleMap);}//使用stream流实现转换List<Map> collect = users.stream().map(user -> {Map 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;}}