Java提取对象集合的某些属性生成新集合

本文介绍了如何在Java中不使用实体类的情况下,通过Stream API将List集合中的对象元素投影到新的属性,生成新的集合。示例展示了从UserEntity对象中提取userName和phone创建Map集合,以及提取id和userName创建另一个Map集合的过程。这种方法在处理集合数据时提供了灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


有时候在对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("昵称", "无名")));
}

输出结果:
在这里插入图片描述
本次记录就到这里了。

行到水穷处,坐看云起时。——王维《终南别业 / 初至山中 / 入山寄城中故人》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值