我想使用Java 8的流和lambda将对象列表转换为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的情况下执行此操作。
在番石榴:
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();
        }
    });
}带有Java 8 lambda的番石榴。
private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}
Maps.uniqueIndex(choices, Choice::getName)。