为了账号安全,请及时绑定邮箱和手机立即绑定

Java 8列表<V>到地图<K,V>

Java 8列表<V>到地图<K,V>

繁花如伊 2019-07-01 14:59:30
Java 8列表<V>到地图<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;}我可以使用Java 8和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羔羊。private Map<String, Choice> nameMap(List<Choice> choices) {     return Maps.uniqueIndex(choices, Choice::getName);}
查看完整描述

3 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

基于Collectors文献资料它很简单,就像:

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


查看完整回答
反对 回复 2019-07-01
?
当年话下

TA贡献1890条经验 获得超9个赞

如果你的钥匙是保证对列表中的所有元素都是唯一的,则应该将其转换为Map<String, List<Choice>>而不是Map<String, Choice>

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


查看完整回答
反对 回复 2019-07-01
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

这里还有一个,以防您不想使用Collection tors.toMap()

Map<String, Choice> result =
   choices.stream().collect(HashMap<String, Choice>::new, 
                           (m, c) -> m.put(c.getName(), c),
                           (m, u) -> {});


查看完整回答
反对 回复 2019-07-01
  • 3 回答
  • 0 关注
  • 693 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号