Java 8中如何将List<V>转换为Map<K, V>呢?
下文笔者讲述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));
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。