Java复制Bean,List工具类

public class CopyBeanUtil {

    /**
     * 复制对象
     *
     * @param source 源 要复制的对象
     * @param target 目标 复制到此对象
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, Class<T> target) {
        try {
            T newInstance = target.newInstance();
            BeanUtils.copyProperties(source, newInstance);
            return newInstance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制list
     *
     * @param source
     * @param target
     * @param <T>
     * @param <K>
     * @return
     */
    public static <T, K> List<K> copyList(List<T> source, Class<K> target) {

        if (null == source || source.isEmpty()) {
            return Collections.emptyList();
        }
        return source.stream().map(e -> copy(e, target)).collect(Collectors.toList());
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Hutool 工具包中的 `BeanUtil` 类来将一个 List 转换为一个 Map。 示例代码如下: ```java import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import java.util.List; import java.util.Map; public class Test { public static void main(String[] args) { // 假设有一个类 User,有属性 id、name、age List<User> userList = CollUtil.newArrayList( new User(1L, "张三", 20), new User(2L, "李四", 21), new User(3L, "王五", 22) ); // 将 List 转为 Map,以 id 为 key,User 对象为 value Map<Long, User> userMap = CollUtil.toMap(userList, user -> user.getId(), user -> user); // 打印转换后的 Map System.out.println(userMap); } static class User { private Long id; private String name; private Integer age; public User(Long id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } } } ``` 在上面的示例代码中,我们使用 `CollUtil.toMap()` 方法将 List 转为 Map,其中第一个参数是要转换的 List,第二个参数是 key 的获取方式,第三个参数是 value 的获取方式。在本例中,我们将 id 作为 key,User 对象作为 value。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值