相关疑难解决方法(0)

Java 8将<V>列入Map <K,V>

我想使用Java 8的流和lambdas将对象列表转换为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;
}
Run Code Online (Sandbox Code Playgroud)

我可以使用Java 8和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();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

还有Java 8 lambda的番石榴.

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

java lambda java-8 java-stream

892
推荐指数
16
解决办法
60万
查看次数

标签 统计

java ×1

java-8 ×1

java-stream ×1

lambda ×1