关于list集合stream流转换为map集合

img


本人刚学没多久看的黑马的java课讲课老师没有提到怎么转为map集合求大佬写个代码我看一下是怎么写的自己试了老久都是错的😭😭😭

public static void main(String[] args) throws Exception {
        List<String> stringList = Arrays.asList("tom", "tohka", "yoxino");
        // Collectors.toMap
        // 第一个参数,map中key怎么生成,Function.identity()的意思是拿stringList中的元素本身
        // 第二个参数,map中value怎么生成,我这边是直接在stringList元素后拼接后缀-value
        // 第三个参数,map中key重复时怎么处理,我这边写的表达式意思是:保持原有的不变,即不覆盖
        Map<String, String> stringMap = stringList.stream()
                .collect(Collectors.toMap(Function.identity(), item -> item + "-value", (k1, k2) -> k1));
        System.out.println(stringMap);
    }

参考:https://rumenz.com/examples/java8/java8-stream-list-to-map.html

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632