Java 8 的List<V> 转成 Map<K, V> | Java Debug 笔记

本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看 活动链接

问题: Java 8 的List 转成 Map<K, V>

我想要使用Java 8的streams和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;
}
复制代码

我可以很轻松地用Java8和Guava搞定,但是呢我又不知道怎么不用Guava搞定

Guava写法:

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写法:

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}
复制代码

回答一:

基于Collectors 文档,可以简写成为:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));
复制代码

回答二

如果你的key不保证对于每个list中每个元素都是独一无二的,你就应该转换成Map<String, List>而不是Map<String, Choice>

Map<String, List<Choice>> result =
 choices.stream().collect(Collectors.groupingBy(Choice::getName));
复制代码

回答三

用 getName() 作为 key 并且Choice 本身作为map的value:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));
复制代码

回答四

上述的大部分回答的忽略了一种情况了就是当list有重复元素的时候。这种情况下就会抛出 IllegalStateException,参考下面的代码去处理重复的list元素吧

public Map<String, Choice> convertListToMap(List<Choice> choices) {
    return choices.stream()
        .collect(Collectors.toMap(Choice::getName, choice -> choice,
            (oldValue, newValue) -> newValue));
  }
复制代码

回答五

例如你想转换对象的一些域到map上:

对象是:

class Item{
        private String code;
        private String name;

        public Item(String code, String name) {
            this.code = code;
            this.name = name;
        }

        //getters and setters
    }
复制代码

List 转 Map的操作是:

List<Item> list = new ArrayList<>();
list.add(new Item("code1", "name1"));
list.add(new Item("code2", "name2"));

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

复制代码

文章翻译自Stack Overflow:stackoverflow.com/questions/2…

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享