《零散代码块 · 列表转换键值对象》

大家好,我是 【战神刘玉栋】,有10多年的研发经验,致力于前后端技术栈的知识沉淀和传播。
CSDN入驻不久,希望大家多多支持,后续会继续提升文章质量,绝不滥竽充数,欢迎多多交流。

文章目录

    • 写在前面的话
    • 将列表转换为键值对象
    • 总结陈词

CSDN.gif

写在前面的话

本系列博文进行一些Java开发日常代码块分享。


将列表转换为键值对象

**场景一:**无论后端还是前端,都有这个场景,后端List(或前端Array),通常不能直接用来渲染使用,根据某个属性,转换为后端Map(或前端JSON对象),方便后续使用。

List<LwUserInfo> dataList = new ArrayList<>();
Map<String, List<LwUserInfo>> userNameMap = new HashMap<>(16);
for (LwUserInfo lwUserInfo : dataList) {
    String name = lwUserInfo.getNickName();
    if (userNameMap.containsKey(name)) {
        userNameMap.get(name).add(lwUserInfo);
    } else {
        List<LwUserInfo> tempList = new ArrayList<>();
        tempList.add(lwUserInfo);
        userNameMap.put(name, tempList);
    }
}

**场景二:**仅仅根据List里面每个对象的元素作为Key,对象本身作为Map,这种转换就很简单了。

// 范例1,Key 和 Value 都是 String
Map<String, String> storeNameMap = ckStoreDicts.stream()
    .collect(Collectors.toMap(CkStoreDict::getStoreCode, CkStoreDict::getStoreName));

// 范例2,Value 是对象本身,两种写法
Map<String, CkDeptDict> map = ckDeptDicts.stream()
    .collect(Collectors.toMap(CkDeptDict::getDeptCode, Function.identity()));
Map<String, CkDeptDict> map2 = ckDeptDicts.stream()
    .collect(Collectors.toMap(CkDeptDict::getDeptCode, a -> a));

总结陈词

后续会逐步分享企业实际开发中的实战经验,有需要交流的可以联系博主。

CSDN_END.gif

你可能感兴趣的:(后端程序猿,spring,boot,后端,java)