Object转List

1.背景

工作中经常会遇到一个map存key为string类型 value存object,方便我们下文代码获取数据

2.例如
java 复制代码
Map<String, Object> result= new HashMap<>();
List<Map<String, Object>> sheet1Result = new ArrayList<>();
List<String> headMap = new ArrayList();
result.put("sheet1Result", sheet1Result);
result.put("sheet1ResultHeadMap", headMap);

上述这种情况就是,一个map存在多个类型

下文获取需要将object转为list

3.方法
java 复制代码
	//object转为List
    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
java 复制代码
	//object转为Map<key,value>
   public static <K, V> List<Map<K, V>> castListMap(Object obj, Class<K> kCalzz, Class<V> vCalzz) {
        List<Map<K, V>> result = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object mapObj : (List<?>) obj) {
                if (mapObj instanceof Map<?, ?>) {
                    Map<K, V> map = new HashMap<>(16);
                    for (Map.Entry<?, ?> entry : ((Map<?, ?>) mapObj).entrySet()) {
                        map.put(kCalzz.cast(entry.getKey()), vCalzz.cast(entry.getValue()));
                    }
                    result.add(map);
                }
            }
            return result;
        }
        return null;
    }
相关推荐
多恩Stone1 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc1 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@1 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.1 小时前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
偷心伊普西隆1 小时前
Python EXCEL 理论探究:格式转换时处理缺失值方法
python·excel
精灵vector2 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain
java1234_小锋3 小时前
Scikit-learn Python机器学习 - 特征降维 压缩数据 - 特征选择 - 移除低方差特征(VarianceThreshold)
python·机器学习·scikit-learn
万邦科技Lafite3 小时前
实战演练:通过API获取商品详情并展示
大数据·数据库·python·开放api接口