Java 8列表与流映射 [英] Java 8 list to map with stream

查看:148
本文介绍了Java 8列表与流映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< Item> 集合。
我需要将它转换为 Map< Integer,Item>
地图的键必须是集合中项目的索引。
我无法弄清楚如何使用流。
类似的东西:

I have a List<Item> collection. I need to convert it into Map<Integer, Item> The key of the map must be the index of the item in the collection. I can not figure it out how to do this with streams. Something like:

items.stream().collect(Collectors.toMap(...));

有任何帮助吗?

被标识为可能的重复我需要添加,我的具体问题是 - 如何获取列表中的项目的位置,并将其作为键值

As this question is identified as possible duplicate I need to add that my concrete problem was - how to get the position of the item in the list and put it as a key value

推荐答案

您可以使用 IntStream 创建 Stream 的索引,然后将它们转换为a Map

You can create a Stream of the indices using an IntStream and then convert them to a Map :

Map<Integer,Item> map = 
    IntStream.range(0,items.size())
             .boxed()
             .collect(Collectors.toMap (i -> i, i -> items.get(i)));

这篇关于Java 8列表与流映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆