有时候在对List集合操作时并不想新建一个实体类来进行转换。这就涉及到将集合中对象的每个元素投影到新属性,以此来生成一个新的集合。
一、准备工作
定义实体类UserEntity
@Data
public class UserEntity implements Serializable {
private Integer id;
/**
* 用户名
*/
private String userName;
/**
* 用户手机号
*/
private String phone;
public UserEntity(Integer id,String userName,String phone) {
this.id = id;
this.userName = userName;
this.phone = phone;
}
}
二、操作实例
public static void main(String[] args) {
List<UserEntity> users = new ArrayList<>();
users.add(new UserEntity(1, "张三", "123131"));
users.add(new UserEntity(2, "李四", "123132"));
users.add(new UserEntity(3, "王五", "123131"));
System.out.println("原始数据+++++++++++++++++++++++++++++++++++++++++");
users.forEach(System.out::println);
System.out.println("对象中的每个元素投影到属性++++++++++++++++++++++");
List<Map> lis_new = users.stream().map(new Function<UserEntity, Map>() {
@Override
public Map apply(UserEntity userEntity) {
Map map = new HashMap();
map.put("姓名", userEntity.getUserName());
map.put("电话", userEntity.getPhone());
return map;
}
}).collect(Collectors.toList());
lis_new.forEach(System.out::println);
System.out.println("--------------------------------------------------");
List<Map> lis_new1 = users.stream().map(new Function<UserEntity, Map>() {
@Override
public Map apply(UserEntity userEntity) {
Map map = new HashMap();
map.put("标识", userEntity.getId());
map.put("昵称", userEntity.getUserName());
return map;
}
}).collect(Collectors.toList());
lis_new1.forEach(System.out::println);
System.out.println("获取属性-----------------------------------------");
lis_new1.stream().forEach(val -> System.out.println(val.getOrDefault("标识", "0") + ":" + val.getOrDefault("昵称", "无名")));
}
输出结果:
本次记录就到这里了。
行到水穷处,坐看云起时。——王维《终南别业 / 初至山中 / 入山寄城中故人》