如何Java 8将List<V>转换成Map<K, V> | Java Debug 笔记

447 阅读1分钟

提问:

背景:

我想用Java 8的流和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;
}

我可以用Java 8和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();
        }
    });
}

And Guava with Java 8 lambdas.

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

回答:

根据收藏家的描述,这很简单~

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