简体   繁体   English

使用Maps.uniqueIndex时如何获取当前索引

[英]How to get hold of current index when using Maps.uniqueIndex

We have a List of items: List<X> from this List, we would like to create Map<F(X), X> 我们有一个项目List<X>List<X> ,我们想要创建Map<F(X), X>

using Guava com.google.common.collect , there is Maps.uniqueIndex method, which takes a List as an input and allows us to apply a function to elements. 使用Guava com.google.common.collect ,有Maps.uniqueIndex方法,它将List作为输入并允许我们将函数应用于元素。

this is all great. 这一切都很棒。 for example: 例如:

List<File> to Map<String, File>

mapOfFileNames = Maps.uniqueIndex(fileList, new Function<File, String>() {
            @Override
            public String apply(@Nullable File input) {
                return input.getName();
            }
        });

my question is, how we can get hold of position of the current Item (index) in the List, when using Maps.uniqueIndex 我的问题是,当使用Maps.uniqueIndex时,我们如何能够获得List中当前Item (index)的位置

for example, to convert List<File> to Map<Integer, File> I would like keys to be the position of File element in the List. 例如,要将List<File> to Map<Integer, File>转换List<File> to Map<Integer, File>我希望将键作为List中File元素的位置。 therefore I need to get access to the index of the current element. 因此我需要访问当前元素的索引。

do you know how this can be possible ? 你知道这怎么可能吗?

Thank You 谢谢

Why do you want to do this? 你为什么要这样做? I don't really see the usefulness of it, given that you can do lookups in a List by index anyway. 鉴于你无论如何都可以通过索引在List进行查找,我真的没有看到它的用处。 Getting the index of the input item in the Function would be wasteful because you'd have to do an indexOf for each item. 获取Function输入项的索引将是浪费,因为您必须为每个项执行indexOf If you really want to do this, I'd say just do: 如果你真的想这样做,我会说:

List<File> list = ...
Map<Integer, File> map = Maps.newHashMap();
for (int i = 0; i < list.size(); i++) {
  map.put(i, list.get(i));
}

On a related note, all ImmutableCollection s have an asList() view, which could allow you to do index-based lookup on any ImmutableMap . 在相关的说明中,所有ImmutableCollection都有一个asList()视图,它允许您对任何ImmutableMap进行基于索引的查找。 Maps.uniqueIndex also preserves the order from the original collection. Maps.uniqueIndex还保留原始集合的顺序。 Using your example: 使用你的例子:

ImmutableMap<String, File> mapOfFileNames = Maps.uniqueIndex(...);
/*
 * The entry containing the file that was at index 5 in the original list
 * and its filename.
 */
Map.Entry<String, File> entry = mapOfFileNames.entrySet().asList().get(5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM