Java 8中如何将List<V>转换为Map<K, V>呢?

戚薇 Java经验 发布时间:2023-05-22 22:25:39 阅读数:18525 1
下文笔者讲述list转Map的方法分享,如下所示

List转Map的实现思路

1.for循环将List转换为Map
2.使用Guava的写法
3.借助java8中的Lambdas进行list和map的转换

Java 7

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

Guava转换List为Map

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

Guava +Java 8 lambdas将list转换为map

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}
 
例:List转Map示例
List<Item> list = new ArrayList<>();
list.add(new Item("code1", "java265.com-1"));
list.add(new Item("code2", "java265.com-2"));

Map<String,String> map = list.stream()
     .collect(Collectors.toMap(Item::getCode, Item::getName));
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202305/16847655806574.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者